Tìm thấy video : học cơ bản js

Bài 1: Javascript Turorial App - Covid Tracker API

Chưa có bình luận 1336
Javascript Cơ Bản, Javascript App, Web Javascript, Học Javascript, Học Js Cơ Bản, Javascript Kết Hợp Api, Javascript Với Api, Api App, Học Cơ Bản Js, Học Cơ Bản Javascript, Javascipt Covid, Covid Tracker Js, Website Với Javacript, Javacript Là Gì, Javascipt Api, Ja,
File index.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Covid19 Tracker</title>
	<!-- Latest compiled and minified CSS -->
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

	<style type="text/css">
		ul.list_world {
		    padding: 0;
		    margin: 0;
		    list-style: none;
		}
		ul.list_world li {
	    border: 1px dashed #000;
	    width: 24%;
	    padding: 10px;
	    margin: 5px;
	    background: beige;
	    float: left;
	    height: 280px;
		}
	</style>

</head>
<body>
	<div class="container">
		<div class="col-md-12">
			<h3>COVID-19 tracker</h3>
			<p>Link API Covid : <a href="">https://github.com/ExpDev07/coronavirus-tracker-api</a></p>
			
			<p>Theo dõi tình trạng covid tại : <span id="title"></span></p>
			<select id="select_world">
				<option value="">---Chọn quốc gia---</option>
			</select>
			 <table class="table table-striped">
			    <thead>
			      <tr>
			      	<th>ID</th>
			        <th>Quốc gia</th>
			        <th>Mã Quốc gia</th>
			        <th>Dân số</th>
			        <th>Bị nhiễm</th>
			        <th>Tử vong</th>
			        <th>Hồi phục</th>
			        <th>Cập nhật gần nhất</th>
			        <th>% tử vong</th>
			      </tr>
			    </thead>
			    <tbody>
			      <tr>
			      	<td><div id="id"></div></td>
			        <td><span style="color:red" id="quocgia"></span><span style="color:red" id="tinh"></span></td>
			        <td><div id="code"></div></td>
			        <td><div id="danso"></div></td>
			        <td><div id="canhiem"></div></td>
			        <td><div id="tuvong"></div></td>
			        <td><div id="hoiphuc"></div></td>
			        <td><div id="capnhat"></div></td>
			        <td><div id="phantram"></div></td>
			      </tr>
			      
			    </tbody>
			  </table>
			  <!-------world--------->

			  <p>Theo dõi tình trạng covid toàn thế giới</p>
			  <p>Ca nhiễm : <span id="tong_canhiem"></span> ca</p>
			  <p>Tử vong : <span id="tong_tuvong"></span></p>
			  <p>Phục hồi : <span id="tong_phuchoi"></span></p>


			  <div id="list"></div>
			  
		</div>
	</div>

</body>
	<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script type="text/javascript" src="app.js"></script>
</html>

File App.js

getCovidWorld();
getCovidCountry();
getSelectCountry();
const btnSelect = document.getElementById("select_world");
btnSelect.addEventListener("click",getCountryById);

function getCountryById(e){
	
	fetch('https://coronavirus-tracker-api.herokuapp.com/v2/locations/'+e.target.value)
	.then(res => res.json())
	.then(data => {
		
		let id = data.location.id;
		let code = data.location.country_code;
		let tinh = data.location.province;
		let quocgia = data.location.country;
		let danso = data.location.country_population;
		let capnhat = data.location.last_updated;
		let canhiem = data.location.latest.confirmed;
		let hoiphuc = data.location.latest.recovered;
		let tuvong = data.location.latest.deaths;

		if(data.location.province!=""){
			document.getElementById("quocgia").innerHTML = quocgia.toLocaleString('en') + '-' + tinh.toLocaleString('en');
			document.getElementById("title").innerText = quocgia.toLocaleString('en') + '-' + tinh.toLocaleString('en');
			document.getElementById("tinh").innerHTML = '-' + tinh.toLocaleString('en');
		}else{
			document.getElementById("quocgia").innerHTML = quocgia.toLocaleString('en');
			document.getElementById("title").innerText = quocgia.toLocaleString('en');
		}

		document.getElementById("id").innerHTML = id;
		document.getElementById("quocgia").innerHTML = quocgia.toLocaleString("en");
		document.getElementById("code").innerHTML = code.toLocaleString("en");
		document.getElementById("danso").innerHTML = danso.toLocaleString("en");
		document.getElementById("capnhat").innerHTML = capnhat.substring(0,10);
		document.getElementById("canhiem").innerHTML = canhiem.toLocaleString("en");
		document.getElementById("tuvong").innerHTML = tuvong.toLocaleString("en");
		document.getElementById("hoiphuc").innerHTML = hoiphuc.toLocaleString("en");
		document.getElementById('phantram').innerHTML = ((Number(tuvong)/Number(canhiem))*100).toLocaleString("en", {minimumFractionDigits: 2, maximumFractionDigits: 2} ) + "%";
	}).catch(error => console.log('Error'));
}
function getCovidCountry(){
	fetch('https://coronavirus-tracker-api.herokuapp.com/v2/locations/266')
	.then(res => res.json())
	.then(data => {
		
		let id = data.location.id;
		let code = data.location.country_code;
		let quocgia = data.location.country;
		let tinh = data.location.province;
		let danso = data.location.country_population;
		let capnhat = data.location.last_updated;
		let canhiem = data.location.latest.confirmed;
		let hoiphuc = data.location.latest.recovered;
		let tuvong = data.location.latest.deaths;

		if(data.location.province!=""){
			document.getElementById("quocgia").innerHTML = quocgia.toLocaleString('en') + '-' + tinh.toLocaleString('en');
			document.getElementById("title").innerText = quocgia.toLocaleString('en') + '-' + tinh.toLocaleString('en');
			document.getElementById("tinh").innerHTML = '-' + tinh.toLocaleString('en');
		}else{
			document.getElementById("quocgia").innerHTML = quocgia.toLocaleString('en');
			document.getElementById("title").innerText = quocgia.toLocaleString('en');
		}


		document.getElementById("id").innerHTML = id;
		document.getElementById("quocgia").innerHTML = quocgia.toLocaleString("en");
		document.getElementById("code").innerHTML = code.toLocaleString("en");
		document.getElementById("danso").innerHTML = danso.toLocaleString("en");
		document.getElementById("capnhat").innerHTML = capnhat.substring(0,10);
		document.getElementById("canhiem").innerHTML = canhiem.toLocaleString("en");
		document.getElementById("tuvong").innerHTML = tuvong.toLocaleString("en");
		document.getElementById("hoiphuc").innerHTML = hoiphuc.toLocaleString("en");
		document.getElementById('phantram').innerHTML = ((Number(tuvong)/Number(canhiem))*100).toLocaleString("en", {minimumFractionDigits: 2, maximumFractionDigits: 2} ) + "%";
	}).catch(error => console.log('Error'));;
	
}
function getCovidWorld(){
	fetch('https://coronavirus-tracker-api.herokuapp.com/v2/locations')
	.then(res => res.json())
	.then(data => {
		console.log(data);

		let nguoinhiem = data.latest.confirmed;
		let chet = data.latest.deaths;
		let phuchoi = data.latest.recovered;
		document.getElementById("tong_canhiem").innerHTML = new Intl.NumberFormat().format(nguoinhiem);
		document.getElementById("tong_tuvong").innerHTML = chet.toLocaleString("en");
		document.getElementById("tong_phuchoi").innerHTML = phuchoi.toLocaleString("en");

		const html = data.locations.map(covid => {

			const id = covid.id;
			const code = covid.country_code;
			const quocgia = covid.country;
			const tinh = covid.province;
			const danso = covid.country_population;
			const capnhat = covid.last_updated;
			const canhiem = covid.latest.confirmed;
			const hoiphuc = covid.latest.recovered;
			const tuvong = covid.latest.deaths;

			return `
			<ul class="list_world">
			<li>
			<p>id:${id}</p>
			<p style='color:red'>Quốc gia:${quocgia.toLocaleString("en")}</p>
			<p style='color:blue'>${tinh.toLocaleString("en")}</p>
			<p>Mã Quốc gia:${code}</p>
			<p>Dân số:${new Intl.NumberFormat().format(danso)}</p>
			<p>Cập nhật:${capnhat.substring(0,10)}</p>
			<p>Ca nhiễm:${new Intl.NumberFormat().format(canhiem)}</p>
			<p>Tử vong:${new Intl.NumberFormat().format(tuvong)}</p>
			<p>Phần trăm:${
				((Number(tuvong)/Number(canhiem))*100).toLocaleString("en", {minimumFractionDigits: 2, maximumFractionDigits: 2} ) + "%"}
				</p>

				</li>

				</ul>
				`

			}).join("");
		document.getElementById("list").insertAdjacentHTML("afterbegin",html);

	}).catch(error => console.log('Error'));;
}
function getSelectCountry(){
	fetch('https://coronavirus-tracker-api.herokuapp.com/v2/locations')
	.then(res => res.json())
	.then(data => {
		
		const html = data.locations.map(list => {

			const id = list.id;
			const quocgia = list.country;

			var option = document.createElement('option');
			option.value = id;
			if(list.province!=""){
				option.innerHTML = quocgia + '-' + list.province;
			}else{
				option.innerHTML = quocgia;
			}
			
			document.getElementById("select_world").appendChild(option);	

		});

	}).catch(error => console.log('Error'));;
}

 


Bài 2: Javascript Turorial App - Todo List

Chưa có bình luận 1118
Javascript Cơ Bản, Javascript App, Web Javascript, Học Javascript, Học Js Cơ Bản, Javascript Kết Hợp Api, Javascript Với Api, Api App, Học Cơ Bản Js, Học Cơ Bản Javascript, Javascipt Covid, Covid Tracker Js, Website Với Javacript, Javacript Là Gì, Javascipt Api, Ja,

File index.html

 

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>My Todo List</title>
	<!-- Latest compiled and minified CSS -->
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
	<link rel="preconnect" href="https://fonts.gstatic.com">
	<link href="https://fonts.googleapis.com/css2?family=Oswald:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">
	<!-- Latest compiled and minified JavaScript -->
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
	<style type="text/css">
		body{
			font-family: 'Oswald', sans-serif;
		}
		.completed{
			text-decoration: line-through;
    		opacity: 0.5;
		}
	</style>
</head>
<body>
	<div class="container">
		<h3 style="text-align: center;text-transform: uppercase;font-size: 20px">My Todo List</h3>
		<div class="col-md-6">
			<form>
				<input type="text" class="form-control" id="input_value">
				<input type="submit" id="btn_todo" class="btn btn-sm btn-primary" value="Thêm" style="margin:5px 0"><br>
				<div class="select">
					<select id="select_todo" class="form-control">
						<option value="tatca">Tất cả công việc</option>
						<option value="hoanthanh">Hoàn thành</option>
						<option value="chuahoanthanh">Chưa hoàn thành</option>
					</select>
				</div>
			</form>
			<div class="todo-container">
				<ul id="todo-list"></ul>
			</div>
		
		</div>
	</div>
	<script type="text/javascript" src="app.js"></script>

</body>

</html>

 

File App.js

const input_value = document.getElementById("input_value");
const btn_todo = document.getElementById("btn_todo");
const list_todo = document.getElementById("todo-list");
const filter_todo = document.getElementById("select_todo");

document.addEventListener("DOMContentLoaded", listTodoStorage);
btn_todo.addEventListener("click",addtodo);
list_todo.addEventListener("click",deleteTodo);
filter_todo.addEventListener("click",filterTodo);

function filterTodo(e) {
  const task = list_todo.childNodes;
  task.forEach(function(todo) {
    switch (e.target.value) {
      case "tatca":
        todo.style.display = "block";
        break;
      case "hoanthanh":
        if (todo.classList.contains("completed")) {
          todo.style.display = "block";
        } else {
          todo.style.display = "none";
        }
        break;
      case "chuahoanthanh":
        if (!todo.classList.contains("completed")) {
          todo.style.display = "block";
        } else {
          todo.style.display = "none";
        }
        break;
    }
  });
}

function addtodo(e){
	e.preventDefault();
	todo = input_value.value;
	if(todo){

		const newDiv = document.createElement("div");
		newDiv.classList.add('todo');
		//tao list todo
		const newTodo = document.createElement("li");
		newTodo.innerText = todo;
		newTodo.classList.add('todo-item');
		newDiv.appendChild(newTodo);
		//add to local
		saveLocalStorage(todo);
		input_value.value = "";
		const btn_hoanthanh = document.createElement("button");
		btn_hoanthanh.innerText = "Hoàn thành";
		btn_hoanthanh.classList.add("completed_btn");
		newDiv.appendChild(btn_hoanthanh);

		const btn_xoa = document.createElement("button");
		btn_xoa.innerText = "Xóa";
		btn_xoa.classList.add("delete_btn");
		newDiv.appendChild(btn_xoa);

		list_todo.appendChild(newDiv);

		

	}
}
function deleteTodo(e){
	const item = e.target;
	//delete todo
	if(item.classList[0]==='delete_btn'){
		const todo = item.parentElement;
		todo.remove();
		removeStorageToDo(todo);
	}
	//completed button
	if(item.classList[0]==='completed_btn'){
		const todo = item.parentElement;
		todo.classList.toggle("completed");
		updateStorageItem(todo);
	}

}	

function saveLocalStorage(todo){
	let task;
	if(localStorage.getItem("task")===null){
		task = [];
	}else{
		task = JSON.parse(localStorage.getItem("task"))
	}
	task.push({
		text:todo,
		complete:false
	});
	localStorage.setItem("task", JSON.stringify(task));
}

function listTodoStorage(){
	let task;
	if(localStorage.getItem("task")===null){
		task = [];
	}else{
		task = JSON.parse(localStorage.getItem("task"))
	}
	task.forEach(nhiemvu => {
		const newDiv = document.createElement("div");
		newDiv.classList.add('todo');
		//tao list todo
		const newTodo = document.createElement("li");
		newTodo.innerText = nhiemvu.text;
		newTodo.classList.add('todo-item');
		newDiv.appendChild(newTodo);
	
		const btn_hoanthanh = document.createElement("button");
		btn_hoanthanh.innerText = "Hoàn thành";
		btn_hoanthanh.classList.add("completed_btn");
		newDiv.appendChild(btn_hoanthanh);

		const btn_xoa = document.createElement("button");
		btn_xoa.innerText = "Xóa";
		btn_xoa.classList.add("delete_btn");
		newDiv.appendChild(btn_xoa);

		list_todo.appendChild(newDiv);

		if(nhiemvu.complete == true){
			newDiv.classList.add('completed');
			btn_hoanthanh.innerText = "Đã hoàn thành";
			btn_hoanthanh.style.color = "green";
			btn_hoanthanh.disabled = true;
		}
	})
	
}
function updateStorageItem(todo){
	let task;
	if(localStorage.getItem("task")===null){
		task = [];
	}else{
		task = JSON.parse(localStorage.getItem("task"))
	}
	const todoIndex = todo.children[0].innerText;

	index = task.findIndex(object => object.text === todoIndex);
	task[index].complete = true;
	localStorage.setItem("task", JSON.stringify(task));
}
function removeStorageToDo(todo){
	let task;
	if(localStorage.getItem("task")===null){
		task = [];
	}else{
		task = JSON.parse(localStorage.getItem("task"))
	}
	const todoIndex = todo.children[0].innerText;
	task.splice(task.indexOf(todoIndex),1);
	localStorage.setItem("task", JSON.stringify(task));
}



 


Bài 3: Javascript Turorial App - Kết thức phần Covid Tracker API

Chưa có bình luận 1190
Javascript Cơ Bản, Javascript App, Web Javascript, Học Javascript, Học Js Cơ Bản, Javascript Kết Hợp Api, Javascript Với Api, Api App, Học Cơ Bản Js, Học Cơ Bản Javascript, Javascipt Covid, Covid Tracker Js, Website Với Javacript, Javacript Là Gì, Javascipt Api, Ja,
File Index.html
File index.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Covid19 Tracker</title>
	<!-- Latest compiled and minified CSS -->
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

	<style type="text/css">
		ul.list_world {
		    padding: 0;
		    margin: 0;
		    list-style: none;
		}
		ul.list_world li {
	    border: 1px dashed #000;
	    width: 24%;
	    padding: 10px;
	    margin: 5px;
	    background: beige;
	    float: left;
	    height: 280px;
		}
	</style>

</head>
<body>
	<div class="container">
		<div class="col-md-12">
			<h3>COVID-19 tracker</h3>
			<p>Link API Covid : <a href="">https://github.com/ExpDev07/coronavirus-tracker-api</a></p>
			
			<p>Theo dõi tình trạng covid tại : <span id="title"></span></p>
			<select id="select_world">
				<option value="">---Chọn quốc gia---</option>
			</select>
			 <table class="table table-striped">
			    <thead>
			      <tr>
			      	<th>ID</th>
			        <th>Quốc gia</th>
			        <th>Mã Quốc gia</th>
			        <th>Dân số</th>
			        <th>Bị nhiễm</th>
			        <th>Tử vong</th>
			        <th>Hồi phục</th>
			        <th>Cập nhật gần nhất</th>
			        <th>% tử vong</th>
			      </tr>
			    </thead>
			    <tbody>
			      <tr>
			      	<td><div id="id"></div></td>
			        <td><span style="color:red" id="quocgia"></span><span style="color:red" id="tinh"></span></td>
			        <td><div id="code"></div></td>
			        <td><div id="danso"></div></td>
			        <td><div id="canhiem"></div></td>
			        <td><div id="tuvong"></div></td>
			        <td><div id="hoiphuc"></div></td>
			        <td><div id="capnhat"></div></td>
			        <td><div id="phantram"></div></td>
			      </tr>
			      
			    </tbody>
			  </table>
			  <!-------world--------->

			  <p>Theo dõi tình trạng covid toàn thế giới</p>
			  <p>Ca nhiễm : <span id="tong_canhiem"></span> ca</p>
			  <p>Tử vong : <span id="tong_tuvong"></span></p>
			  <p>Phục hồi : <span id="tong_phuchoi"></span></p>


			  <div id="list"></div>
			  
		</div>
	</div>

</body>
	<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script type="text/javascript" src="app.js"></script>
</html>

File App.js

 

getCovidWorld();
getCovidCountry();
getSelectCountry();
const btnSelect = document.getElementById("select_world");
btnSelect.addEventListener("click",getCountryById);

function getCountryById(e){
	
	fetch('https://coronavirus-tracker-api.herokuapp.com/v2/locations/'+e.target.value)
	.then(res => res.json())
	.then(data => {
		
		let id = data.location.id;
		let code = data.location.country_code;
		let tinh = data.location.province;
		let quocgia = data.location.country;
		let danso = data.location.country_population;
		let capnhat = data.location.last_updated;
		let canhiem = data.location.latest.confirmed;
		let hoiphuc = data.location.latest.recovered;
		let tuvong = data.location.latest.deaths;

		if(data.location.province!=""){
			document.getElementById("quocgia").innerHTML = quocgia.toLocaleString('en') + '-' + tinh.toLocaleString('en');
			document.getElementById("title").innerText = quocgia.toLocaleString('en') + '-' + tinh.toLocaleString('en');
			document.getElementById("tinh").innerHTML = '-' + tinh.toLocaleString('en');
		}else{
			document.getElementById("quocgia").innerHTML = quocgia.toLocaleString('en');
			document.getElementById("title").innerText = quocgia.toLocaleString('en');
		}

		document.getElementById("id").innerHTML = id;
		document.getElementById("quocgia").innerHTML = quocgia.toLocaleString("en");
		document.getElementById("code").innerHTML = code.toLocaleString("en");
		document.getElementById("danso").innerHTML = danso.toLocaleString("en");
		document.getElementById("capnhat").innerHTML = capnhat.substring(0,10);
		document.getElementById("canhiem").innerHTML = canhiem.toLocaleString("en");
		document.getElementById("tuvong").innerHTML = tuvong.toLocaleString("en");
		document.getElementById("hoiphuc").innerHTML = hoiphuc.toLocaleString("en");
		document.getElementById('phantram').innerHTML = ((Number(tuvong)/Number(canhiem))*100).toLocaleString("en", {minimumFractionDigits: 2, maximumFractionDigits: 2} ) + "%";
	}).catch(error => console.log('Error'));
}
function getCovidCountry(){
	fetch('https://coronavirus-tracker-api.herokuapp.com/v2/locations/266')
	.then(res => res.json())
	.then(data => {
		
		let id = data.location.id;
		let code = data.location.country_code;
		let quocgia = data.location.country;
		let tinh = data.location.province;
		let danso = data.location.country_population;
		let capnhat = data.location.last_updated;
		let canhiem = data.location.latest.confirmed;
		let hoiphuc = data.location.latest.recovered;
		let tuvong = data.location.latest.deaths;

		if(data.location.province!=""){
			document.getElementById("quocgia").innerHTML = quocgia.toLocaleString('en') + '-' + tinh.toLocaleString('en');
			document.getElementById("title").innerText = quocgia.toLocaleString('en') + '-' + tinh.toLocaleString('en');
			document.getElementById("tinh").innerHTML = '-' + tinh.toLocaleString('en');
		}else{
			document.getElementById("quocgia").innerHTML = quocgia.toLocaleString('en');
			document.getElementById("title").innerText = quocgia.toLocaleString('en');
		}


		document.getElementById("id").innerHTML = id;
		document.getElementById("quocgia").innerHTML = quocgia.toLocaleString("en");
		document.getElementById("code").innerHTML = code.toLocaleString("en");
		document.getElementById("danso").innerHTML = danso.toLocaleString("en");
		document.getElementById("capnhat").innerHTML = capnhat.substring(0,10);
		document.getElementById("canhiem").innerHTML = canhiem.toLocaleString("en");
		document.getElementById("tuvong").innerHTML = tuvong.toLocaleString("en");
		document.getElementById("hoiphuc").innerHTML = hoiphuc.toLocaleString("en");
		document.getElementById('phantram').innerHTML = ((Number(tuvong)/Number(canhiem))*100).toLocaleString("en", {minimumFractionDigits: 2, maximumFractionDigits: 2} ) + "%";
	}).catch(error => console.log('Error'));;
	
}
function getCovidWorld(){
	fetch('https://coronavirus-tracker-api.herokuapp.com/v2/locations')
	.then(res => res.json())
	.then(data => {
		console.log(data);

		let nguoinhiem = data.latest.confirmed;
		let chet = data.latest.deaths;
		let phuchoi = data.latest.recovered;
		document.getElementById("tong_canhiem").innerHTML = new Intl.NumberFormat().format(nguoinhiem);
		document.getElementById("tong_tuvong").innerHTML = chet.toLocaleString("en");
		document.getElementById("tong_phuchoi").innerHTML = phuchoi.toLocaleString("en");

		const html = data.locations.map(covid => {

			const id = covid.id;
			const code = covid.country_code;
			const quocgia = covid.country;
			const tinh = covid.province;
			const danso = covid.country_population;
			const capnhat = covid.last_updated;
			const canhiem = covid.latest.confirmed;
			const hoiphuc = covid.latest.recovered;
			const tuvong = covid.latest.deaths;

			return `
			<ul class="list_world">
			<li>
			<p>id:${id}</p>
			<p style='color:red'>Quốc gia:${quocgia.toLocaleString("en")}</p>
			<p style='color:blue'>${tinh.toLocaleString("en")}</p>
			<p>Mã Quốc gia:${code}</p>
			<p>Dân số:${new Intl.NumberFormat().format(danso)}</p>
			<p>Cập nhật:${capnhat.substring(0,10)}</p>
			<p>Ca nhiễm:${new Intl.NumberFormat().format(canhiem)}</p>
			<p>Tử vong:${new Intl.NumberFormat().format(tuvong)}</p>
			<p>Phần trăm:${
				((Number(tuvong)/Number(canhiem))*100).toLocaleString("en", {minimumFractionDigits: 2, maximumFractionDigits: 2} ) + "%"}
				</p>

				</li>

				</ul>
				`

			}).join("");
		document.getElementById("list").insertAdjacentHTML("afterbegin",html);

	}).catch(error => console.log('Error'));;
}
function getSelectCountry(){
	fetch('https://coronavirus-tracker-api.herokuapp.com/v2/locations')
	.then(res => res.json())
	.then(data => {
		
		const html = data.locations.map(list => {

			const id = list.id;
			const quocgia = list.country;

			var option = document.createElement('option');
			option.value = id;
			if(list.province!=""){
				option.innerHTML = quocgia + '-' + list.province;
			}else{
				option.innerHTML = quocgia;
			}
			
			document.getElementById("select_world").appendChild(option);	

		});

	}).catch(error => console.log('Error'));;
}

 


Bài 4: Javascript Turorial App - Todo List #2

Chưa có bình luận 1041
Javascript Cơ Bản, Javascript App, Web Javascript, Học Javascript, Học Js Cơ Bản, Javascript Kết Hợp Api, Javascript Với Api, Api App, Học Cơ Bản Js, Học Cơ Bản Javascript, Javascipt Covid, Covid Tracker Js, Website Với Javacript, Javacript Là Gì, Javascipt Api, Ja,

File index.html

 

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>My Todo List</title>
	<!-- Latest compiled and minified CSS -->
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
	<link rel="preconnect" href="https://fonts.gstatic.com">
	<link href="https://fonts.googleapis.com/css2?family=Oswald:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">
	<!-- Latest compiled and minified JavaScript -->
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
	<style type="text/css">
		body{
			font-family: 'Oswald', sans-serif;
		}
		.completed{
			text-decoration: line-through;
    		opacity: 0.5;
		}
	</style>
</head>
<body>
	<div class="container">
		<h3 style="text-align: center;text-transform: uppercase;font-size: 20px">My Todo List</h3>
		<div class="col-md-6">
			<form>
				<input type="text" class="form-control" id="input_value">
				<input type="submit" id="btn_todo" class="btn btn-sm btn-primary" value="Thêm" style="margin:5px 0"><br>
				<div class="select">
					<select id="select_todo" class="form-control">
						<option value="tatca">Tất cả công việc</option>
						<option value="hoanthanh">Hoàn thành</option>
						<option value="chuahoanthanh">Chưa hoàn thành</option>
					</select>
				</div>
			</form>
			<div class="todo-container">
				<ul id="todo-list"></ul>
			</div>
		
		</div>
	</div>
	<script type="text/javascript" src="app.js"></script>

</body>

</html>

 

File App.js

const input_value = document.getElementById("input_value");
const btn_todo = document.getElementById("btn_todo");
const list_todo = document.getElementById("todo-list");
const filter_todo = document.getElementById("select_todo");

document.addEventListener("DOMContentLoaded", listTodoStorage);
btn_todo.addEventListener("click",addtodo);
list_todo.addEventListener("click",deleteTodo);
filter_todo.addEventListener("click",filterTodo);

function filterTodo(e) {
  const task = list_todo.childNodes;
  task.forEach(function(todo) {
    switch (e.target.value) {
      case "tatca":
        todo.style.display = "block";
        break;
      case "hoanthanh":
        if (todo.classList.contains("completed")) {
          todo.style.display = "block";
        } else {
          todo.style.display = "none";
        }
        break;
      case "chuahoanthanh":
        if (!todo.classList.contains("completed")) {
          todo.style.display = "block";
        } else {
          todo.style.display = "none";
        }
        break;
    }
  });
}

function addtodo(e){
	e.preventDefault();
	todo = input_value.value;
	if(todo){

		const newDiv = document.createElement("div");
		newDiv.classList.add('todo');
		//tao list todo
		const newTodo = document.createElement("li");
		newTodo.innerText = todo;
		newTodo.classList.add('todo-item');
		newDiv.appendChild(newTodo);
		//add to local
		saveLocalStorage(todo);
		input_value.value = "";
		const btn_hoanthanh = document.createElement("button");
		btn_hoanthanh.innerText = "Hoàn thành";
		btn_hoanthanh.classList.add("completed_btn");
		newDiv.appendChild(btn_hoanthanh);

		const btn_xoa = document.createElement("button");
		btn_xoa.innerText = "Xóa";
		btn_xoa.classList.add("delete_btn");
		newDiv.appendChild(btn_xoa);

		list_todo.appendChild(newDiv);

		

	}
}
function deleteTodo(e){
	const item = e.target;
	//delete todo
	if(item.classList[0]==='delete_btn'){
		const todo = item.parentElement;
		todo.remove();
		removeStorageToDo(todo);
	}
	//completed button
	if(item.classList[0]==='completed_btn'){
		const todo = item.parentElement;
		todo.classList.toggle("completed");
		updateStorageItem(todo);
	}

}	

function saveLocalStorage(todo){
	let task;
	if(localStorage.getItem("task")===null){
		task = [];
	}else{
		task = JSON.parse(localStorage.getItem("task"))
	}
	task.push({
		text:todo,
		complete:false
	});
	localStorage.setItem("task", JSON.stringify(task));
}

function listTodoStorage(){
	let task;
	if(localStorage.getItem("task")===null){
		task = [];
	}else{
		task = JSON.parse(localStorage.getItem("task"))
	}
	task.forEach(nhiemvu => {
		const newDiv = document.createElement("div");
		newDiv.classList.add('todo');
		//tao list todo
		const newTodo = document.createElement("li");
		newTodo.innerText = nhiemvu.text;
		newTodo.classList.add('todo-item');
		newDiv.appendChild(newTodo);
	
		const btn_hoanthanh = document.createElement("button");
		btn_hoanthanh.innerText = "Hoàn thành";
		btn_hoanthanh.classList.add("completed_btn");
		newDiv.appendChild(btn_hoanthanh);

		const btn_xoa = document.createElement("button");
		btn_xoa.innerText = "Xóa";
		btn_xoa.classList.add("delete_btn");
		newDiv.appendChild(btn_xoa);

		list_todo.appendChild(newDiv);

		if(nhiemvu.complete == true){
			newDiv.classList.add('completed');
			btn_hoanthanh.innerText = "Đã hoàn thành";
			btn_hoanthanh.style.color = "green";
			btn_hoanthanh.disabled = true;
		}
	})
	
}
function updateStorageItem(todo){
	let task;
	if(localStorage.getItem("task")===null){
		task = [];
	}else{
		task = JSON.parse(localStorage.getItem("task"))
	}
	const todoIndex = todo.children[0].innerText;

	index = task.findIndex(object => object.text === todoIndex);
	task[index].complete = true;
	localStorage.setItem("task", JSON.stringify(task));
}
function removeStorageToDo(todo){
	let task;
	if(localStorage.getItem("task")===null){
		task = [];
	}else{
		task = JSON.parse(localStorage.getItem("task"))
	}
	const todoIndex = todo.children[0].innerText;
	task.splice(task.indexOf(todoIndex),1);
	localStorage.setItem("task", JSON.stringify(task));
}




Bài 5: Javascript Turorial App - Kết thúc Todo List

Chưa có bình luận 1090
Javascript Cơ Bản, Javascript App, Web Javascript, Học Javascript, Học Js Cơ Bản, Javascript Kết Hợp Api, Javascript Với Api, Api App, Học Cơ Bản Js, Học Cơ Bản Javascript, Javascipt Covid, Covid Tracker Js, Website Với Javacript, Javacript Là Gì, Javascipt Api, Ja,

File index.html

 

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>My Todo List</title>
	<!-- Latest compiled and minified CSS -->
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
	<link rel="preconnect" href="https://fonts.gstatic.com">
	<link href="https://fonts.googleapis.com/css2?family=Oswald:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">
	<!-- Latest compiled and minified JavaScript -->
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
	<style type="text/css">
		body{
			font-family: 'Oswald', sans-serif;
		}
		.completed{
			text-decoration: line-through;
    		opacity: 0.5;
		}
	</style>
</head>
<body>
	<div class="container">
		<h3 style="text-align: center;text-transform: uppercase;font-size: 20px">My Todo List</h3>
		<div class="col-md-6">
			<form>
				<input type="text" class="form-control" id="input_value">
				<input type="submit" id="btn_todo" class="btn btn-sm btn-primary" value="Thêm" style="margin:5px 0"><br>
				<div class="select">
					<select id="select_todo" class="form-control">
						<option value="tatca">Tất cả công việc</option>
						<option value="hoanthanh">Hoàn thành</option>
						<option value="chuahoanthanh">Chưa hoàn thành</option>
					</select>
				</div>
			</form>
			<div class="todo-container">
				<ul id="todo-list"></ul>
			</div>
		
		</div>
	</div>
	<script type="text/javascript" src="app.js"></script>

</body>

</html>

 

File App.js

const input_value = document.getElementById("input_value");
const btn_todo = document.getElementById("btn_todo");
const list_todo = document.getElementById("todo-list");
const filter_todo = document.getElementById("select_todo");

document.addEventListener("DOMContentLoaded", listTodoStorage);
btn_todo.addEventListener("click",addtodo);
list_todo.addEventListener("click",deleteTodo);
filter_todo.addEventListener("click",filterTodo);

function filterTodo(e) {
  const task = list_todo.childNodes;
  task.forEach(function(todo) {
    switch (e.target.value) {
      case "tatca":
        todo.style.display = "block";
        break;
      case "hoanthanh":
        if (todo.classList.contains("completed")) {
          todo.style.display = "block";
        } else {
          todo.style.display = "none";
        }
        break;
      case "chuahoanthanh":
        if (!todo.classList.contains("completed")) {
          todo.style.display = "block";
        } else {
          todo.style.display = "none";
        }
        break;
    }
  });
}

function addtodo(e){
	e.preventDefault();
	todo = input_value.value;
	if(todo){

		const newDiv = document.createElement("div");
		newDiv.classList.add('todo');
		//tao list todo
		const newTodo = document.createElement("li");
		newTodo.innerText = todo;
		newTodo.classList.add('todo-item');
		newDiv.appendChild(newTodo);
		//add to local
		saveLocalStorage(todo);
		input_value.value = "";
		const btn_hoanthanh = document.createElement("button");
		btn_hoanthanh.innerText = "Hoàn thành";
		btn_hoanthanh.classList.add("completed_btn");
		newDiv.appendChild(btn_hoanthanh);

		const btn_xoa = document.createElement("button");
		btn_xoa.innerText = "Xóa";
		btn_xoa.classList.add("delete_btn");
		newDiv.appendChild(btn_xoa);

		list_todo.appendChild(newDiv);

		

	}
}
function deleteTodo(e){
	const item = e.target;
	//delete todo
	if(item.classList[0]==='delete_btn'){
		const todo = item.parentElement;
		todo.remove();
		removeStorageToDo(todo);
	}
	//completed button
	if(item.classList[0]==='completed_btn'){
		const todo = item.parentElement;
		todo.classList.toggle("completed");
		updateStorageItem(todo);
	}

}	

function saveLocalStorage(todo){
	let task;
	if(localStorage.getItem("task")===null){
		task = [];
	}else{
		task = JSON.parse(localStorage.getItem("task"))
	}
	task.push({
		text:todo,
		complete:false
	});
	localStorage.setItem("task", JSON.stringify(task));
}

function listTodoStorage(){
	let task;
	if(localStorage.getItem("task")===null){
		task = [];
	}else{
		task = JSON.parse(localStorage.getItem("task"))
	}
	task.forEach(nhiemvu => {
		const newDiv = document.createElement("div");
		newDiv.classList.add('todo');
		//tao list todo
		const newTodo = document.createElement("li");
		newTodo.innerText = nhiemvu.text;
		newTodo.classList.add('todo-item');
		newDiv.appendChild(newTodo);
	
		const btn_hoanthanh = document.createElement("button");
		btn_hoanthanh.innerText = "Hoàn thành";
		btn_hoanthanh.classList.add("completed_btn");
		newDiv.appendChild(btn_hoanthanh);

		const btn_xoa = document.createElement("button");
		btn_xoa.innerText = "Xóa";
		btn_xoa.classList.add("delete_btn");
		newDiv.appendChild(btn_xoa);

		list_todo.appendChild(newDiv);

		if(nhiemvu.complete == true){
			newDiv.classList.add('completed');
			btn_hoanthanh.innerText = "Đã hoàn thành";
			btn_hoanthanh.style.color = "green";
			btn_hoanthanh.disabled = true;
		}
	})
	
}
function updateStorageItem(todo){
	let task;
	if(localStorage.getItem("task")===null){
		task = [];
	}else{
		task = JSON.parse(localStorage.getItem("task"))
	}
	const todoIndex = todo.children[0].innerText;

	index = task.findIndex(object => object.text === todoIndex);
	task[index].complete = true;
	localStorage.setItem("task", JSON.stringify(task));
}
function removeStorageToDo(todo){
	let task;
	if(localStorage.getItem("task")===null){
		task = [];
	}else{
		task = JSON.parse(localStorage.getItem("task"))
	}
	const todoIndex = todo.children[0].innerText;
	task.splice(task.indexOf(todoIndex),1);
	localStorage.setItem("task", JSON.stringify(task));
}




Bài 6: Javascript Turorial App - Recipe App

Chưa có bình luận 1629
Javascript Cơ Bản, Javascript App, Web Javascript, Học Javascript, Học Js Cơ Bản, Javascript Kết Hợp Api, Javascript Với Api, Api App, Học Cơ Bản Js, Học Cơ Bản Javascript, Javascipt Covid, Covid Tracker Js, Website Với Javacript, Javacript Là Gì, Javascipt Api, Ja,

File index.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Recipe App</title>
	<!-- Latest compiled and minified CSS -->
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
	<link rel="preconnect" href="https://fonts.gstatic.com">
	<link href="https://fonts.googleapis.com/css2?family=Rubik:ital,wght@0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap" rel="stylesheet">
	<!-- Latest compiled and minified JavaScript -->
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

	<style type="text/css">

	body{
		font-family: 'Rubik', sans-serif;
		background: rgb(26, 26, 27);
	}
	ul.list_food {
		list-style: none;
	}
	ul.list_food li {
		border: 1px solid #fff;
		width: 23%;
		float: left;
		padding: 10px;
		margin:10px;
		color: #fff;
		padding: 10px; 
		height: 480px;
	}
	.li_recipe span {
		color: orangered;
		font-weight: bold;
	}
	h3.title_recipe {

		text-align: center;
		color: #fff;
		font-size: 40px;
		font-weight: bold;
	}
	form.search-form {
		width: 60%;
		display: block;
		margin: 0 auto;
	}
</style>
</head>
<body>
	<div class="container">
		<h3 class="title_recipe">Recipe App</h3>
		<div class="col-md-12">

			<form class="search-form">

				<input type="text" class="input_meal form-control" placeholder="Tìm kiếm công thức nấu ăn VD: Beef">
				
				<input type="submit" style="margin:5px 0" class="btn btn-default btn-sm btn-search" value="Tìm kiếm món">

			</form>
			
			<p style="color: #fff;text-align: center;font-size: 16px;text-transform: uppercase;"><span id="title"></span></p>
			
		</div>
		<div class="col-md-12">
			<ul class="list_food">
				<div class="li_recipe"></div>	
			</ul>
		</div>
	</div>
	<script type="text/javascript" src="app.js"></script>
</body>
</html>

File App.js

const input = document.querySelector(".input_meal");
const btn = document.querySelector(".btn-search");


btn.addEventListener("click",getMeal);

function getMeal(e){
  e.preventDefault();
  input_value = input.value;
  document.getElementById("title").innerText = 'Công thức tìm kiếm từ:'+' '+input.value;
  fetchDataAPI(input_value);
}

async function fetchDataAPI(input_value){
  app_id = '24270fcf';
  app_key = '9c8b546d8fefe29384d4e2e11755885e';
  baseURI = `https://api.edamam.com/search?q=${input_value}&app_id=${app_id}&app_key=${app_key}`;
  result = await fetch(baseURI);
  datas = await result.json();
  createHTML(datas.hits);
}
function createHTML(data){
	console.log(data);
	showHtml = '';
	data.map(result => {
		showHtml+= `<li>
					<img width="100%" src="${result.recipe.image}">
					<p>Tên món ăn : <span>${result.recipe.label}</span></p>
					<p>Calories : <span>${result.recipe.calories.toFixed(2)}</span></p>
					<p>Ăn kiêng : <span>${result.recipe.dietLabels.length > 0 ? result.recipe.dietLabels : 'No Data Found'}</span></p>
					<p>Tốt cho sức khỏe : <span>${result.recipe.healthLabels}</span></p>
					<a href="${result.recipe.url}" 
					target="_blank" class="btn btn-sm btn-primary">View Recipe</a>
				</li>`;
	})
	document.querySelector(".li_recipe").innerHTML = showHtml;
}

 


Bài 7: Javascript Turorial App - CountDown Times

Chưa có bình luận 1115
Javascript Cơ Bản, Javascript App, Web Javascript, Học Javascript, Học Js Cơ Bản, Javascript Kết Hợp Api, Javascript Với Api, Api App, Học Cơ Bản Js, Học Cơ Bản Javascript, Javascipt Covid, Covid Tracker Js, Website Với Javacript, Javacript Là Gì, Javascipt Api, Ja,

Ứng dụng Javascipt App đếm ngược thời gian tới năm mới.

File Index.html


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Countdown Timer</title>
        <link rel="stylesheet" href="style.css" />
        <script src="script.js" defer></script>
    </head>
    <body>
        <h1>New Years Eve</h1>

        <div class="countdown-container">
            <div class="countdown-el days-c">
                <p class="big-text" id="days">0</p>
                <span>days</span>
            </div>
            <div class="countdown-el hours-c">
                <p class="big-text" id="hours">0</p>
                <span>hours</span>
            </div>
            <div class="countdown-el mins-c">
                <p class="big-text" id="mins">0</p>
                <span>mins</span>
            </div>
            <div class="countdown-el seconds-c">
                <p class="big-text" id="seconds">0</p>
                <span>seconds</span>
            </div>
        </div>
    </body>
</html>

File Style.css

@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@200;400;600&display=swap");

* {
    box-sizing: border-box;
}

body {
    background-image: url("./snow.jpg");
    background-size: cover;
    background-position: center center;
    display: flex;
    flex-direction: column;
    align-items: center;
    min-height: 100vh;
    font-family: "Poppins", sans-serif;
    margin: 0;
}

h1 {
    font-weight: normal;
    font-size: 4rem;
    margin-top: 5rem;
}

.countdown-container {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
}

.big-text {
    font-weight: bold;
    font-size: 6rem;
    line-height: 1;
    margin: 1rem 2rem;
}

.countdown-el {
    text-align: center;
}

.countdown-el span {
    font-size: 1.3rem;
}

File App.js

const daysEl = document.getElementById("days");
const hoursEl = document.getElementById("hours");
const minsEl = document.getElementById("mins");
const secondsEl = document.getElementById("seconds");

const newYears = "1 Jan 2021";

function countdown() {
    const newYearsDate = new Date(newYears);
    const currentDate = new Date();

    const totalSeconds = (newYearsDate - currentDate) / 1000;

    const days = Math.floor(totalSeconds / 3600 / 24);
    const hours = Math.floor(totalSeconds / 3600) % 24;
    const mins = Math.floor(totalSeconds / 60) % 60;
    const seconds = Math.floor(totalSeconds) % 60;

    daysEl.innerHTML = days;
    hoursEl.innerHTML = formatTime(hours);
    minsEl.innerHTML = formatTime(mins);
    secondsEl.innerHTML = formatTime(seconds);
}

function formatTime(time) {
    return time < 10 ? `0${time}` : time;
}

// initial call
countdown();

setInterval(countdown, 1000);

 


Bài 8: Javascript Turorial App - Drawing App

Chưa có bình luận 949
Javascript Cơ Bản, Javascript App, Web Javascript, Học Javascript, Học Js Cơ Bản, Javascript Kết Hợp Api, Javascript Với Api, Api App, Học Cơ Bản Js, Học Cơ Bản Javascript, Javascipt Covid, Covid Tracker Js, Website Với Javacript, Javacript Là Gì, Javascipt Api, Ja,

Ứng dụng vẽ bằng JS 

File index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Drawing App</title>
        <link rel="stylesheet" href="style.css" />
        <script src="script.js" defer></script>
    </head>
    <body>
        <canvas id="canvas" width="800" height="800"></canvas>
        <div class="toolbox">
            <button id="decrease">-</button>
            <span id="size">30</span>
            <button id="increase">+</button>
            <input type="color" id="color" />
            <button id="clear">????</button>
        </div>
    </body>
</html>

File Style.css

@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@200;400;600&display=swap");

* {
    box-sizing: border-box;
}

body {
    background-color: #f5f5f5;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-family: "Poppins", sans-serif;
    margin: 0;
    min-height: 100vh;
}

canvas {
    border: 2px solid rebeccapurple;
}

.toolbox {
    background-color: rebeccapurple;
    border: 1px solid rebeccapurple;
    display: flex;
    padding: 1rem;
    width: 804px;
}

.toolbox > * {
    background-color: #fff;
    border: none;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 2rem;
    padding: 0.25rem;
    margin: 0.25rem;
    height: 50px;
    width: 50px;
}

.toolbox > *:last-child {
    margin-left: auto;
}

 

File App.js

const canvas = document.getElementById("canvas");
const increaseBtn = document.getElementById("increase");
const decreaseBtn = document.getElementById("decrease");
const sizeEl = document.getElementById("size");
const colorEl = document.getElementById("color");
const clearEl = document.getElementById("clear");
const ctx = canvas.getContext("2d");

let size = 30;
let isPressed = false;
let color = "black";
let x = undefined;
let y = undefined;

canvas.addEventListener("mousedown", (e) => {
    isPressed = true;

    x = e.offsetX;
    y = e.offsetY;
});

canvas.addEventListener("mouseup", (e) => {
    isPressed = false;

    x = undefined;
    y = undefined;
});

canvas.addEventListener("mousemove", (e) => {
    if (isPressed) {
        const x2 = e.offsetX;
        const y2 = e.offsetY;

        drawCircle(x2, y2);
        drawLine(x, y, x2, y2);
        x = x2;
        y = y2;
    }
});

function drawCircle(x, y) {
    ctx.beginPath();
    ctx.arc(x, y, size, 0, Math.PI * 2);
    ctx.fillStyle = color;
    ctx.fill();
}

function drawLine(x1, y1, x2, y2) {
    ctx.beginPath();
    ctx.moveTo(x1, y1);
    ctx.lineTo(x2, y2);
    ctx.strokeStyle = color;
    ctx.lineWidth = size * 2;
    ctx.stroke();
}

increaseBtn.addEventListener("click", () => {
    size += 5;

    if (size > 50) {
        size = 50;
    }

    updateSizeOnScreen();
});

decreaseBtn.addEventListener("click", () => {
    size -= 5;

    if (size < 5) {
        size = 5;
    }

    updateSizeOnScreen();
});

colorEl.addEventListener("change", (e) => {
    color = e.target.value;
});

clearEl.addEventListener("click", () => {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
});

function updateSizeOnScreen() {
    sizeEl.innerText = size;
}

 

 


Bài 9: Javascript Turorial App - Movie App

Chưa có bình luận 967
Javascript Cơ Bản, Javascript App, Web Javascript, Học Javascript, Học Js Cơ Bản, Javascript Kết Hợp Api, Javascript Với Api, Api App, Học Cơ Bản Js, Học Cơ Bản Javascript, Javascipt Covid, Website Với Javacript, Javacript Là Gì, Javascipt Api, Javascript Php, Php ,

Ứng dụng Website phim bằng Js 

Javascript movie App

File index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Movie App</title>
        <link rel="stylesheet" href="style.css" />
        <script src="script.js" defer></script>
    </head>
    <body>
        <header>
            <form id="form">
                <input
                    type="text"
                    id="search"
                    placeholder="Search"
                    class="search"
                />
            </form>
        </header>
        <main id="main"></main>
    </body>
</html>

File Style.css

@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@200;400;600&display=swap");

* {
    box-sizing: border-box;
}

body {
    background-color: #22254b;
    font-family: "Poppins", sans-serif;
    margin: 0;
}

header {
    background-color: #373b69;
    display: flex;
    justify-content: flex-end;
    padding: 1rem;
}

.search {
    background-color: transparent;
    border: 2px solid #22254b;
    border-radius: 50px;
    color: #fff;
    font-family: inherit;
    font-size: 1rem;
    padding: 0.5rem 1rem;
}

.search::placeholder {
    color: #7378c5;
}

.search:focus {
    background-color: #22254b;
    outline: none;
}

main {
    display: flex;
    flex-wrap: wrap;
}

.movie {
    background-color: #373b69;
    border-radius: 3px;
    box-shadow: 0 4px 5px rgba(0, 0, 0, 0.2);
    overflow: hidden;
    position: relative;
    margin: 1rem;
    width: 300px;
}

.movie img {
    width: 100%;
}

.movie-info {
    color: #eee;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0.5rem 1rem 1rem;
    letter-spacing: 0.5px;
}

.movie-info h3 {
    margin: 0;
}

.movie-info span {
    background-color: #22254b;
    border-radius: 3px;
    font-weight: bold;
    padding: 0.25rem 0.5rem;
}
.movie-info span.green {
    color: rgb(39, 189, 39);
}

.movie-info span.orange {
    color: orange;
}

.movie-info span.red {
    color: rgb(189, 42, 42);
}

.overview {
    background-color: #fff;
    padding: 2rem;
    position: absolute;
    max-height: 100%;
    overflow: auto;
    left: 0;
    bottom: 0;
    right: 0;
    transform: translateY(101%);
    transition: transform 0.3s ease-in;
}

.overview h3 {
    margin-top: 0;
}

.movie:hover .overview {
    transform: translateY(0);
}

File script.js


const APIURL =
    "https://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=04c35731a5ee918f014970082a0088b1&page=1";
const IMGPATH = "https://image.tmdb.org/t/p/w1280";
const SEARCHAPI =
    "https://api.themoviedb.org/3/search/movie?&api_key=04c35731a5ee918f014970082a0088b1&query=";

const main = document.getElementById("main");
const form = document.getElementById("form");
const search = document.getElementById("search");

// initially get fav movies
getMovies(APIURL);

async function getMovies(url) {
    const resp = await fetch(url);
    const respData = await resp.json();

    console.log(respData);

    showMovies(respData.results);
}

function showMovies(movies) {
    // clear main
    main.innerHTML = "";

    movies.forEach((movie) => {
        const { poster_path, title, vote_average, overview } = movie;

        const movieEl = document.createElement("div");
        movieEl.classList.add("movie");

        movieEl.innerHTML = `
            <img
                src="${IMGPATH + poster_path}"
                alt="${title}"
            />
            <div class="movie-info">
                <h3>${title}</h3>
                <span class="${getClassByRate(
                    vote_average
                )}">${vote_average}</span>
            </div>
            <div class="overview">
                <h3>Overview:</h3>
                ${overview}
            </div>
        `;

        main.appendChild(movieEl);
    });
}

function getClassByRate(vote) {
    if (vote >= 8) {
        return "green";
    } else if (vote >= 5) {
        return "orange";
    } else {
        return "red";
    }
}

form.addEventListener("submit", (e) => {
    e.preventDefault();

    const searchTerm = search.value;

    if (searchTerm) {
        getMovies(SEARCHAPI + searchTerm);

        search.value = "";
    }
});

Bài 10: Javascript Turorial App - Notes App

Chưa có bình luận 916
Javascript Cơ Bản, Javascript App, Web Javascript, Học Javascript, Học Js Cơ Bản, Javascript Kết Hợp Api, Javascript Với Api, Api App, Học Cơ Bản Js, Học Cơ Bản Javascript, Javascipt Covid, Website Với Javacript, Javacript Là Gì, Javascipt Api, Javascript Php, Php ,

Ứng dụng viết ghi chú bằng js

File index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Notes App</title>
        <link rel="stylesheet" href="style.css" />
        <link
            rel="stylesheet"
            href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css"
        />
        <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/1.1.1/marked.min.js"></script>
        <script src="script.js" defer></script>
    </head>
    <body>
        <button class="add" id="add">
            <i class="fas fa-plus"></i> Add note
        </button>
    </body>
</html>

File style.css

@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@200;400;600&display=swap");

* {
    box-sizing: border-box;
}

body {
    background-color: #7bdaf3;
    display: flex;
    flex-wrap: wrap;
    font-family: "Poppins", sans-serif;
    margin: 0;
    padding-top: 3rem;
}

.add {
    background-color: #9ec862;
    border-radius: 3px;
    border: none;
    color: white;
    cursor: pointer;
    padding: 0.5rem 1rem;
    position: fixed;
    top: 1rem;
    right: 1rem;
}

.note {
    background-color: #fff;
    box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
    margin: 20px;
    height: 400px;
    width: 400px;
}

.note .tools {
    background-color: #9ec862;
    display: flex;
    justify-content: flex-end;
    padding: 0.5rem;
}

.note .tools button {
    background-color: transparent;
    border: none;
    color: #fff;
    cursor: pointer;
    font-size: 1rem;
    margin-left: 0.5rem;
}

.note .main {
    background-color: #eee;
    overflow: hidden;
    height: 400px;
    width: 100%;
}

.note textarea {
    outline: none;
    font-family: inherit;
    font-size: 1.2rem;
    border: none;
    height: 400px;
    width: 100%;
}

.note .hidden {
    display: none;
}

File script.js

const addBtn = document.getElementById("add");

const notes = JSON.parse(localStorage.getItem("notes"));

if (notes) {
    notes.forEach((note) => {
        addNewNote(note);
    });
}

addBtn.addEventListener("click", () => {
    addNewNote();
});

function addNewNote(text = "") {
    const note = document.createElement("div");
    note.classList.add("note");

    note.innerHTML = `
        <div class="notes">
            <div class="tools">
                <button class="edit"><i class="fas fa-edit"></i></button>
                <button class="delete"><i class="fas fa-trash-alt"></i></button>
            </div>
            <div class="main ${text ? "" : "hidden"}"></div>
            <textarea class="${text ? "hidden" : ""}"></textarea>
        </div>
    `;

    const editBtn = note.querySelector(".edit");
    const deleteBtn = note.querySelector(".delete");

    const main = note.querySelector(".main");
    const textArea = note.querySelector("textarea");

    textArea.value = text;
    main.innerHTML = marked(text);

    editBtn.addEventListener("click", () => {
        main.classList.toggle("hidden");
        textArea.classList.toggle("hidden");
    });

    deleteBtn.addEventListener("click", () => {
        note.remove();

        updateLS();
    });

    textArea.addEventListener("input", (e) => {
        const { value } = e.target;

        main.innerHTML = marked(value);

        updateLS();
    });

    document.body.appendChild(note);
}

function updateLS() {
    const notesText = document.querySelectorAll("textarea");

    const notes = [];

    notesText.forEach((note) => {
        notes.push(note.value);
    });

    localStorage.setItem("notes", JSON.stringify(notes));
}

 


Bài 11: Javascript Turorial App - Password Generator

Chưa có bình luận 1046
Javascript Cơ Bản, Javascript App, Web Javascript, Học Javascript, Học Js Cơ Bản, Javascript Kết Hợp Api, Javascript Với Api, Api App, Học Cơ Bản Js, Học Cơ Bản Javascript, Javascipt Covid, Covid Tracker Js, Website Với Javacript, Javacript Là Gì, Javascipt Api, Ja,

Javascript Turorial App - Ứng dụng tạo mật khẩu ngẫu nhiên

Javascript Turorial App - Ứng dụng tạo mật khẩu ngẫu nhiên

 

File Index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Password Generator</title>
        <link rel="stylesheet" href="style.css" />
        <script src="script.js" defer></script>
    </head>
    <body>
        <div class="pw-container">
            <div class="pw-header">
                <div class="pw">
                    <span id="pw">l823Zs78#Css09@</span>
                    <button id="copy">Copy</button>
                </div>
            </div>
            <div class="pw-body">
                <div class="form-control">
                    <label for="len">Password Length</label>
                    <input id="len" value="15" type="number" min="2" max="30" />
                </div>
                <div class="form-control">
                    <label for="upper">Contain Uppercase Letters</label>
                    <input id="upper" type="checkbox" />
                </div>
                <div class="form-control">
                    <label for="lower">Contain Lowercase Letters</label>
                    <input id="lower" type="checkbox" />
                </div>
                <div class="form-control">
                    <label for="number">Contain Numbers</label>
                    <input id="number" type="checkbox" />
                </div>
                <div class="form-control">
                    <label for="symbol">Contain Symbols</label>
                    <input id="symbol" type="checkbox" />
                </div>
                <button class="generate" id="generate">
                    Generate Password
                </button>
            </div>
        </div>
    </body>
</html>

File Style.css

@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@200;400;600&display=swap");

* {
    box-sizing: border-box;
}

body {
    background-color: rebeccapurple;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-family: "Poppins", sans-serif;
    margin: 0;
    min-height: 100vh;
}

.pw-container {
    background-color: rgb(46, 12, 80);
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.5);
    min-width: 400px;
}

.pw-header {
    padding: 1rem;
}

.pw {
    background-color: rgb(69, 28, 109);
    display: flex;
    font-size: 1.5rem;
    align-items: center;
    height: 70px;
    width: 100%;
    position: relative;
    padding: 1rem;
    overflow: auto;
}

.pw button {
    background-color: white;
    border: none;
    color: rgb(29, 2, 56);
    cursor: pointer;
    font-family: inherit;
    font-weight: bold;
    padding: 0.25rem;
    position: absolute;
    top: 0;
    right: 0;
    transform: translate(0, 20%);
    transition: opacity 0.2s ease, transform 0.2s ease;
    opacity: 0;
}

.pw:hover button {
    opacity: 1;
    transform: translate(0, 0%);
}

.pw-body {
    padding: 0 1rem 1rem;
}

.form-control {
    color: #eee;
    display: flex;
    justify-content: space-between;
    margin: 0.75rem 0;
}

.generate {
    background-color: #ecb602;
    border: none;
    color: rebeccapurple;
    cursor: pointer;
    display: block;
    font-size: 1.5rem;
    font-weight: bold;
    padding: 0.75rem;
    margin-top: 1rem;
    width: 100%;
}

File script.js

const pwEl = document.getElementById("pw");
const copyEl = document.getElementById("copy");
const lenEl = document.getElementById("len");
const upperEl = document.getElementById("upper");
const lowerEl = document.getElementById("lower");
const numberEl = document.getElementById("number");
const symbolEl = document.getElementById("symbol");
const generateEl = document.getElementById("generate");

const upperLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const lowerLetters = "abcdefghijklmnopqrstuvwxyz";
const numbers = "0123456789";
const symbols = "!@#$%^&*()_+=";

function getLowercase() {
    return lowerLetters[Math.floor(Math.random() * lowerLetters.length)];
}

function getUppercase() {
    return upperLetters[Math.floor(Math.random() * upperLetters.length)];
}

function getNumber() {
    return numbers[Math.floor(Math.random() * numbers.length)];
}

function getSymbol() {
    return symbols[Math.floor(Math.random() * symbols.length)];
}

function generatePassword() {
    const len = lenEl.value;

    let password = "";

    if (upperEl.checked) {
        password += getUppercase();
    }

    if (lowerEl.checked) {
        password += getLowercase();
    }

    if (numberEl.checked) {
        password += getNumber();
    }

    if (symbolEl.checked) {
        password += getSymbol();
    }

    for (let i = password.length; i < len; i++) {
        const x = generateX();
        password += x;
    }

    pwEl.innerText = password;
}

function generateX() {
    const xs = [];
    if (upperEl.checked) {
        xs.push(getUppercase());
    }

    if (lowerEl.checked) {
        xs.push(getLowercase());
    }

    if (numberEl.checked) {
        xs.push(getNumber());
    }

    if (symbolEl.checked) {
        xs.push(getSymbol());
    }

    if (xs.length === 0) return "";

    return xs[Math.floor(Math.random() * xs.length)];
}

generateEl.addEventListener("click", generatePassword);

copyEl.addEventListener("click", () => {
    const textarea = document.createElement("textarea");
    const password = pwEl.innerText;

    if (!password) {
        return;
    }

    textarea.value = password;
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand("copy");
    textarea.remove();
    alert("Password copied to clipboard");
});

 


Bài 12: Javascript Turorial App - Quiz App

Chưa có bình luận 1177
Javascript Cơ Bản, Javascript App, Web Javascript, Học Javascript, Học Js Cơ Bản, Javascript Kết Hợp Api, Javascript Với Api, Api App, Học Cơ Bản Js, Học Cơ Bản Javascript, Javascipt Covid, Covid Tracker Js, Website Với Javacript, Javacript Là Gì, Javascipt Api, Ja,

Javascript Turorial App - Ứng dụng trắc nghiệm JS

Javascript Turorial App - Ứng dụng trắc nghiệm JS

File index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Quiz App</title>
        <link rel="stylesheet" href="style.css" />
        <script src="script.js" defer></script>
    </head>
    <body>
        <div class="quiz-container" id="quiz">
            <div class="quiz-header">
                <h2 id="question">Question text</h2>
                <ul>
                    <li>
                        <input
                            type="radio"
                            id="a"
                            name="answer"
                            class="answer"
                        />
                        <label id="a_text" for="a">Question</label>
                    </li>
                    <li>
                        <input
                            type="radio"
                            id="b"
                            name="answer"
                            class="answer"
                        />
                        <label id="b_text" for="b">Question</label>
                    </li>
                    <li>
                        <input
                            type="radio"
                            id="c"
                            name="answer"
                            class="answer"
                        />
                        <label id="c_text" for="c">Question</label>
                    </li>
                    <li>
                        <input
                            type="radio"
                            id="d"
                            name="answer"
                            class="answer"
                        />
                        <label id="d_text" for="d">Question</label>
                    </li>
                </ul>
            </div>
            <button id="submit">Submit</button>
        </div>
    </body>
</html>

File Style.css

@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@200;400;600&display=swap");

* {
    box-sizing: border-box;
}

body {
    background-color: #b8c6db;
    background-image: linear-gradient(315deg, #b8c6db 0%, #f5f7fa 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    font-family: "Poppins", sans-serif;
    margin: 0;
    min-height: 100vh;
}

.quiz-container {
    background-color: #fff;
    border-radius: 10px;
    box-shadow: 0 0 10px 2px rgba(100, 100, 100, 0.1);
    overflow: hidden;
    width: 600px;
    max-width: 100%;
}

.quiz-header {
    padding: 4rem;
}

h2 {
    padding: 1rem;
    text-align: center;
    margin: 0;
}

ul {
    list-style-type: none;
    padding: 0;
}

ul li {
    font-size: 1.2rem;
    margin: 1rem 0;
}

ul li label {
    cursor: pointer;
}

button {
    background-color: #8e44ad;
    border: none;
    color: white;
    cursor: pointer;
    display: block;
    font-family: inherit;
    font-size: 1.1rem;
    width: 100%;
    padding: 1.3rem;
}

button:hover {
    background-color: #732d91;
}

button:focus {
    background-color: #5e3370;
    outline: none;
}

File script.js

const quizData = [
    {
        question: "What is the most used programming language in 2019?",
        a: "Java",
        b: "C",
        c: "Python",
        d: "JavaScript",
        correct: "d",
    },
    {
        question: "Who is the President of US?",
        a: "Florin Pop",
        b: "Donald Trump",
        c: "Ivan Saldano",
        d: "Mihai Andrei",
        correct: "b",
    },
    {
        question: "What does HTML stand for?",
        a: "Hypertext Markup Language",
        b: "Cascading Style Sheet",
        c: "Jason Object Notation",
        d: "Helicopters Terminals Motorboats Lamborginis",
        correct: "a",
    },
    {
        question: "What year was JavaScript launched?",
        a: "1996",
        b: "1995",
        c: "1994",
        d: "none of the above",
        correct: "b",
    },
];

const quiz = document.getElementById("quiz");
const answerEls = document.querySelectorAll(".answer");
const questionEl = document.getElementById("question");
const a_text = document.getElementById("a_text");
const b_text = document.getElementById("b_text");
const c_text = document.getElementById("c_text");
const d_text = document.getElementById("d_text");
const submitBtn = document.getElementById("submit");

let currentQuiz = 0;
let score = 0;

loadQuiz();

function loadQuiz() {
    deselectAnswers();

    const currentQuizData = quizData[currentQuiz];

    questionEl.innerText = currentQuizData.question;
    a_text.innerText = currentQuizData.a;
    b_text.innerText = currentQuizData.b;
    c_text.innerText = currentQuizData.c;
    d_text.innerText = currentQuizData.d;
}

function getSelected() {
    let answer = undefined;

    answerEls.forEach((answerEl) => {
        if (answerEl.checked) {
            answer = answerEl.id;
        }
    });

    return answer;
}

function deselectAnswers() {
    answerEls.forEach((answerEl) => {
        answerEl.checked = false;
    });
}

submitBtn.addEventListener("click", () => {
    // check to see the answer
    const answer = getSelected();

    if (answer) {
        if (answer === quizData[currentQuiz].correct) {
            score++;
        }

        currentQuiz++;
        if (currentQuiz < quizData.length) {
            loadQuiz();
        } else {
            quiz.innerHTML = `
                <h2>You answered correctly at ${score}/${quizData.length} questions.</h2>
                
                <button onclick="location.reload()">Reload</button>
            `;
        }
    }
});

 


Bài 13: Javascript Turorial App - Weather App

Chưa có bình luận 1495
Javascript Cơ Bản, Javascript App, Web Javascript, Học Javascript, Học Js Cơ Bản, Javascript Kết Hợp Api, Javascript Với Api, Api App, Học Cơ Bản Js, Học Cơ Bản Javascript, Javascipt Covid, Covid Tracker Js, Website Với Javacript, Javacript Là Gì, Javascipt Api, Ja,

Javascript Turorial App - Viết ứng dụng thời tiết bằng JS

File index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Weather App</title>
        <link rel="stylesheet" href="style.css" />
        <script src="script.js" defer></script>
    </head>
    <body>
        <form id="form">
            <input
                type="text"
                id="search"
                placeholder="Search by location"
                autocomplete="off"
            />
        </form>
        <main id="main"></main>
    </body>
</html>

File style.css

@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@200;400;600&display=swap");

* {
    box-sizing: border-box;
}

body {
    background: linear-gradient(300deg, #ced1d6, #bfc0c0);
    font-family: "Poppins", sans-serif;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin: 0;
    min-height: 100vh;
}

input {
    background-color: #fff;
    border: none;
    border-radius: 25px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
    font-family: inherit;
    font-size: 1rem;
    padding: 1rem;
    min-width: 300px;
}

input:focus {
    outline: none;
}

.weather {
    font-size: 2rem;
    text-align: center;
}

.weather h2 {
    display: flex;
    align-items: center;
    margin-bottom: 0;
}

File script.js

const apikey = "3265874a2c77ae4a04bb96236a642d2f";

const main = document.getElementById("main");
const form = document.getElementById("form");
const search = document.getElementById("search");

const url = (city) =>
    `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apikey}`;

async function getWeatherByLocation(city) {
    const resp = await fetch(url(city), { origin: "cors" });
    const respData = await resp.json();

    console.log(respData);

    addWeatherToPage(respData);
}

function addWeatherToPage(data) {
    const temp = KtoC(data.main.temp);

    const weather = document.createElement("div");
    weather.classList.add("weather");

    weather.innerHTML = `
        <h2><img src="https://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png" /> ${temp}°C <img src="https://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png" /></h2>
        <small>${data.weather[0].main}</small>
    `;

    // cleanup
    main.innerHTML = "";

    main.appendChild(weather);
}

function KtoC(K) {
    return Math.floor(K - 273.15);
}

form.addEventListener("submit", (e) => {
    e.preventDefault();

    const city = search.value;

    if (city) {
        getWeatherByLocation(city);
    }
});

 

 


Bài 14: Javascript Turorial App - Quiz App with timer

Chưa có bình luận 978
Javascript Cơ Bản, Javascript App, Web Javascript, Học Javascript, Học Js Cơ Bản, Javascript Kết Hợp Api, Javascript Với Api, Api App, Học Cơ Bản Js, Học Cơ Bản Javascript, Javascipt Covid, Covid Tracker Js, Website Với Javacript, Javacript Là Gì, Javascipt Api, Ja,

Javascript Turorial App - Viết ứng dụng trắc nghiệm với thời gian

Javascript Turorial App - Viết ứng dụng trắc nghiệm với thời gian

File index.html

<!-- Created By CodingNepal - www.codingnepalweb.com  -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Awesome Quiz App | CodingNepal</title>
    <link rel="stylesheet" href="style.css">
    <!-- FontAweome CDN Link for Icons-->
    <script src="https://kit.fontawesome.com/a076d05399.js"></script>
</head>
<body>
    <!-- start Quiz button -->
    <div class="start_btn"><button>Start Quiz</button></div>

    <!-- Info Box -->
    <div class="info_box">
        <div class="info-title"><span>Some Rules of this Quiz</span></div>
        <div class="info-list">
            <div class="info">1. You will have only <span>15 seconds</span> per each question.</div>
            <div class="info">2. Once you select your answer, it can't be undone.</div>
            <div class="info">3. You can't select any option once time goes off.</div>
            <div class="info">4. You can't exit from the Quiz while you're playing.</div>
            <div class="info">5. You'll get points on the basis of your correct answers.</div>
        </div>
        <div class="buttons">
            <button class="quit">Exit Quiz</button>
            <button class="restart">Continue</button>
        </div>
    </div>

    <!-- Quiz Box -->
    <div class="quiz_box">
        <header>
            <div class="title">Awesome Quiz Application</div>
            <div class="timer">
                <div class="time_left_txt">Time Left</div>
                <div class="timer_sec">15</div>
            </div>
            <div class="time_line"></div>
        </header>
        <section>
            <div class="que_text">
                <!-- Here I've inserted question from JavaScript -->
            </div>
            <div class="option_list">
                <!-- Here I've inserted options from JavaScript -->
            </div>
        </section>

        <!-- footer of Quiz Box -->
        <footer>
            <div class="total_que">
                <!-- Here I've inserted Question Count Number from JavaScript -->
            </div>
            <button class="next_btn">Next Que</button>
        </footer>
    </div>

    <!-- Result Box -->
    <div class="result_box">
        <div class="icon">
            <i class="fas fa-crown"></i>
        </div>
        <div class="complete_text">You've completed the Quiz!</div>
        <div class="score_text">
            <!-- Here I've inserted Score Result from JavaScript -->
        </div>
        <div class="buttons">
            <button class="restart">Replay Quiz</button>
            <button class="quit">Quit Quiz</button>
        </div>
    </div>

    <!-- Inside this JavaScript file I've inserted Questions and Options only -->
    <script src="js/questions.js"></script>

    <!-- Inside this JavaScript file I've coded all Quiz Codes -->
    <script src="js/script.js"></script>

</body>
</html>

File style.css

/* importing google fonts */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap');
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-serif;
}

body{
    background: #007bff;
}

::selection{
    color: #fff;
    background: #007bff;
}

.start_btn,
.info_box,
.quiz_box,
.result_box{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 
                0 6px 20px 0 rgba(0, 0, 0, 0.19);
}

.info_box.activeInfo,
.quiz_box.activeQuiz,
.result_box.activeResult{
    opacity: 1;
    z-index: 5;
    pointer-events: auto;
    transform: translate(-50%, -50%) scale(1);
}

.start_btn button{
    font-size: 25px;
    font-weight: 500;
    color: #007bff;
    padding: 15px 30px;
    outline: none;
    border: none;
    border-radius: 5px;
    background: #fff;
    cursor: pointer;
}

.info_box{
    width: 540px;
    background: #fff;
    border-radius: 5px;
    transform: translate(-50%, -50%) scale(0.9);
    opacity: 0;
    pointer-events: none;
    transition: all 0.3s ease;
}

.info_box .info-title{
    height: 60px;
    width: 100%;
    border-bottom: 1px solid lightgrey;
    display: flex;
    align-items: center;
    padding: 0 30px;
    border-radius: 5px 5px 0 0;
    font-size: 20px;
    font-weight: 600;
}

.info_box .info-list{
    padding: 15px 30px;
}

.info_box .info-list .info{
    margin: 5px 0;
    font-size: 17px;
}

.info_box .info-list .info span{
    font-weight: 600;
    color: #007bff;
}
.info_box .buttons{
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding: 0 30px;
    border-top: 1px solid lightgrey;
}

.info_box .buttons button{
    margin: 0 5px;
    height: 40px;
    width: 100px;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
    border: none;
    outline: none;
    border-radius: 5px;
    border: 1px solid #007bff;
    transition: all 0.3s ease;
}

.quiz_box{
    width: 550px;
    background: #fff;
    border-radius: 5px;
    transform: translate(-50%, -50%) scale(0.9);
    opacity: 0;
    pointer-events: none;
    transition: all 0.3s ease;
}

.quiz_box header{
    position: relative;
    z-index: 2;
    height: 70px;
    padding: 0 30px;
    background: #fff;
    border-radius: 5px 5px 0 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-shadow: 0px 3px 5px 1px rgba(0,0,0,0.1);
}

.quiz_box header .title{
    font-size: 20px;
    font-weight: 600;
}

.quiz_box header .timer{
    color: #004085;
    background: #cce5ff;
    border: 1px solid #b8daff;
    height: 45px;
    padding: 0 8px;
    border-radius: 5px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 145px;
}

.quiz_box header .timer .time_left_txt{
    font-weight: 400;
    font-size: 17px;
    user-select: none;
}

.quiz_box header .timer .timer_sec{
    font-size: 18px;
    font-weight: 500;
    height: 30px;
    width: 45px;
    color: #fff;
    border-radius: 5px;
    line-height: 30px;
    text-align: center;
    background: #343a40;
    border: 1px solid #343a40;
    user-select: none;
}

.quiz_box header .time_line{
    position: absolute;
    bottom: 0px;
    left: 0px;
    height: 3px;
    background: #007bff;
}

section{
    padding: 25px 30px 20px 30px;
    background: #fff;
}

section .que_text{
    font-size: 25px;
    font-weight: 600;
}

section .option_list{
    padding: 20px 0px;
    display: block;   
}

section .option_list .option{
    background: aliceblue;
    border: 1px solid #84c5fe;
    border-radius: 5px;
    padding: 8px 15px;
    font-size: 17px;
    margin-bottom: 15px;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

section .option_list .option:last-child{
    margin-bottom: 0px;
}

section .option_list .option:hover{
    color: #004085;
    background: #cce5ff;
    border: 1px solid #b8daff;
}

section .option_list .option.correct{
    color: #155724;
    background: #d4edda;
    border: 1px solid #c3e6cb;
}

section .option_list .option.incorrect{
    color: #721c24;
    background: #f8d7da;
    border: 1px solid #f5c6cb;
}

section .option_list .option.disabled{
    pointer-events: none;
}

section .option_list .option .icon{
    height: 26px;
    width: 26px;
    border: 2px solid transparent;
    border-radius: 50%;
    text-align: center;
    font-size: 13px;
    pointer-events: none;
    transition: all 0.3s ease;
    line-height: 24px;
}
.option_list .option .icon.tick{
    color: #23903c;
    border-color: #23903c;
    background: #d4edda;
}

.option_list .option .icon.cross{
    color: #a42834;
    background: #f8d7da;
    border-color: #a42834;
}

footer{
    height: 60px;
    padding: 0 30px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-top: 1px solid lightgrey;
}

footer .total_que span{
    display: flex;
    user-select: none;
}

footer .total_que span p{
    font-weight: 500;
    padding: 0 5px;
}

footer .total_que span p:first-child{
    padding-left: 0px;
}

footer button{
    height: 40px;
    padding: 0 13px;
    font-size: 18px;
    font-weight: 400;
    cursor: pointer;
    border: none;
    outline: none;
    color: #fff;
    border-radius: 5px;
    background: #007bff;
    border: 1px solid #007bff;
    line-height: 10px;
    opacity: 0;
    pointer-events: none;
    transform: scale(0.95);
    transition: all 0.3s ease;
}

footer button:hover{
    background: #0263ca;
}

footer button.show{
    opacity: 1;
    pointer-events: auto;
    transform: scale(1);
}

.result_box{
    background: #fff;
    border-radius: 5px;
    display: flex;
    padding: 25px 30px;
    width: 450px;
    align-items: center;
    flex-direction: column;
    justify-content: center;
    transform: translate(-50%, -50%) scale(0.9);
    opacity: 0;
    pointer-events: none;
    transition: all 0.3s ease;
}

.result_box .icon{
    font-size: 100px;
    color: #007bff;
    margin-bottom: 10px;
}

.result_box .complete_text{
    font-size: 20px;
    font-weight: 500;
}

.result_box .score_text span{
    display: flex;
    margin: 10px 0;
    font-size: 18px;
    font-weight: 500;
}

.result_box .score_text span p{
    padding: 0 4px;
    font-weight: 600;
}

.result_box .buttons{
    display: flex;
    margin: 20px 0;
}

.result_box .buttons button{
    margin: 0 10px;
    height: 45px;
    padding: 0 20px;
    font-size: 18px;
    font-weight: 500;
    cursor: pointer;
    border: none;
    outline: none;
    border-radius: 5px;
    border: 1px solid #007bff;
    transition: all 0.3s ease;
}

.buttons button.restart{
    color: #fff;
    background: #007bff;
}

.buttons button.restart:hover{
    background: #0263ca;
}

.buttons button.quit{
    color: #007bff;
    background: #fff;
}

.buttons button.quit:hover{
    color: #fff;
    background: #007bff;
}

File script.js

//selecting all required elements
const start_btn = document.querySelector(".start_btn button");
const info_box = document.querySelector(".info_box");
const exit_btn = info_box.querySelector(".buttons .quit");
const continue_btn = info_box.querySelector(".buttons .restart");
const quiz_box = document.querySelector(".quiz_box");
const result_box = document.querySelector(".result_box");
const option_list = document.querySelector(".option_list");
const time_line = document.querySelector("header .time_line");
const timeText = document.querySelector(".timer .time_left_txt");
const timeCount = document.querySelector(".timer .timer_sec");
// creating an array and passing the number, questions, options, and answers
let questions = [
    {
    numb: 1,
    question: "What does HTML stand for?",
    answer: "Hyper Text Markup Language",
    options: [
      "Hyper Text Preprocessor",
      "Hyper Text Markup Language",
      "Hyper Text Multiple Language",
      "Hyper Tool Multi Language"
    ]
  },
    {
    numb: 2,
    question: "What does CSS stand for?",
    answer: "Cascading Style Sheet",
    options: [
      "Common Style Sheet",
      "Colorful Style Sheet",
      "Computer Style Sheet",
      "Cascading Style Sheet"
    ]
  },
    {
    numb: 3,
    question: "What does PHP stand for?",
    answer: "Hypertext Preprocessor",
    options: [
      "Hypertext Preprocessor",
      "Hypertext Programming",
      "Hypertext Preprogramming",
      "Hometext Preprocessor"
    ]
  },
    {
    numb: 4,
    question: "What does SQL stand for?",
    answer: "Structured Query Language",
    options: [
      "Stylish Question Language",
      "Stylesheet Query Language",
      "Statement Question Language",
      "Structured Query Language"
    ]
  },
    {
    numb: 5,
    question: "What does XML stand for?",
    answer: "eXtensible Markup Language",
    options: [
      "eXtensible Markup Language",
      "eXecutable Multiple Language",
      "eXTra Multi-Program Language",
      "eXamine Multiple Language"
    ]
  },
  // you can uncomment the below codes and make duplicate as more as you want to add question
  // but remember you need to give the numb value serialize like 1,2,3,5,6,7,8,9.....

  //   {
  //   numb: 6,
  //   question: "Your Question is Here",
  //   answer: "Correct answer of the question is here",
  //   options: [
  //     "Option 1",
  //     "option 2",
  //     "option 3",
  //     "option 4"
  //   ]
  // },
];
// if startQuiz button clicked
start_btn.onclick = ()=>{
    info_box.classList.add("activeInfo"); //show info box
}

// if exitQuiz button clicked
exit_btn.onclick = ()=>{
    info_box.classList.remove("activeInfo"); //hide info box
}

// if continueQuiz button clicked
continue_btn.onclick = ()=>{
    info_box.classList.remove("activeInfo"); //hide info box
    quiz_box.classList.add("activeQuiz"); //show quiz box
    showQuetions(0); //calling showQestions function
    queCounter(1); //passing 1 parameter to queCounter
    startTimer(15); //calling startTimer function
    startTimerLine(0); //calling startTimerLine function
}

let timeValue =  15;
let que_count = 0;
let que_numb = 1;
let userScore = 0;
let counter;
let counterLine;
let widthValue = 0;

const restart_quiz = result_box.querySelector(".buttons .restart");
const quit_quiz = result_box.querySelector(".buttons .quit");

// if restartQuiz button clicked
restart_quiz.onclick = ()=>{
    quiz_box.classList.add("activeQuiz"); //show quiz box
    result_box.classList.remove("activeResult"); //hide result box
    timeValue = 15; 
    que_count = 0;
    que_numb = 1;
    userScore = 0;
    widthValue = 0;
    showQuetions(que_count); //calling showQestions function
    queCounter(que_numb); //passing que_numb value to queCounter
    clearInterval(counter); //clear counter
    clearInterval(counterLine); //clear counterLine
    startTimer(timeValue); //calling startTimer function
    startTimerLine(widthValue); //calling startTimerLine function
    timeText.textContent = "Time Left"; //change the text of timeText to Time Left
    next_btn.classList.remove("show"); //hide the next button
}

// if quitQuiz button clicked
quit_quiz.onclick = ()=>{
    window.location.reload(); //reload the current window
}

const next_btn = document.querySelector("footer .next_btn");
const bottom_ques_counter = document.querySelector("footer .total_que");

// if Next Que button clicked
next_btn.onclick = ()=>{
    if(que_count < questions.length - 1){ //if question count is less than total question length
        que_count++; //increment the que_count value
        que_numb++; //increment the que_numb value
        showQuetions(que_count); //calling showQestions function
        queCounter(que_numb); //passing que_numb value to queCounter
        clearInterval(counter); //clear counter
        clearInterval(counterLine); //clear counterLine
        startTimer(timeValue); //calling startTimer function
        startTimerLine(widthValue); //calling startTimerLine function
        timeText.textContent = "Time Left"; //change the timeText to Time Left
        next_btn.classList.remove("show"); //hide the next button
    }else{
        clearInterval(counter); //clear counter
        clearInterval(counterLine); //clear counterLine
        showResult(); //calling showResult function
    }
}

// getting questions and options from array
function showQuetions(index){
    const que_text = document.querySelector(".que_text");

    //creating a new span and div tag for question and option and passing the value using array index
    let que_tag = '<span>'+ questions[index].numb + ". " + questions[index].question +'</span>';
    let option_tag = '<div class="option"><span>'+ questions[index].options[0] +'</span></div>'
    + '<div class="option"><span>'+ questions[index].options[1] +'</span></div>'
    + '<div class="option"><span>'+ questions[index].options[2] +'</span></div>'
    + '<div class="option"><span>'+ questions[index].options[3] +'</span></div>';
    que_text.innerHTML = que_tag; //adding new span tag inside que_tag
    option_list.innerHTML = option_tag; //adding new div tag inside option_tag
    
    const option = option_list.querySelectorAll(".option");

    // set onclick attribute to all available options
    for(i=0; i < option.length; i++){
        option[i].setAttribute("onclick", "optionSelected(this)");
    }
}
// creating the new div tags which for icons
let tickIconTag = '<div class="icon tick"><i class="fas fa-check"></i></div>';
let crossIconTag = '<div class="icon cross"><i class="fas fa-times"></i></div>';

//if user clicked on option
function optionSelected(answer){
    clearInterval(counter); //clear counter
    clearInterval(counterLine); //clear counterLine
    let userAns = answer.textContent; //getting user selected option
    let correcAns = questions[que_count].answer; //getting correct answer from array
    const allOptions = option_list.children.length; //getting all option items
    
    if(userAns == correcAns){ //if user selected option is equal to array's correct answer
        userScore += 1; //upgrading score value with 1
        answer.classList.add("correct"); //adding green color to correct selected option
        answer.insertAdjacentHTML("beforeend", tickIconTag); //adding tick icon to correct selected option
        console.log("Correct Answer");
        console.log("Your correct answers = " + userScore);
    }else{
        answer.classList.add("incorrect"); //adding red color to correct selected option
        answer.insertAdjacentHTML("beforeend", crossIconTag); //adding cross icon to correct selected option
        console.log("Wrong Answer");

        for(i=0; i < allOptions; i++){
            if(option_list.children[i].textContent == correcAns){ //if there is an option which is matched to an array answer 
                option_list.children[i].setAttribute("class", "option correct"); //adding green color to matched option
                option_list.children[i].insertAdjacentHTML("beforeend", tickIconTag); //adding tick icon to matched option
                console.log("Auto selected correct answer.");
            }
        }
    }
    for(i=0; i < allOptions; i++){
        option_list.children[i].classList.add("disabled"); //once user select an option then disabled all options
    }
    next_btn.classList.add("show"); //show the next button if user selected any option
}

function showResult(){
    info_box.classList.remove("activeInfo"); //hide info box
    quiz_box.classList.remove("activeQuiz"); //hide quiz box
    result_box.classList.add("activeResult"); //show result box
    const scoreText = result_box.querySelector(".score_text");
    if (userScore > 3){ // if user scored more than 3
        //creating a new span tag and passing the user score number and total question number
        let scoreTag = '<span>and congrats! ????, You got <p>'+ userScore +'</p> out of <p>'+ questions.length +'</p></span>';
        scoreText.innerHTML = scoreTag;  //adding new span tag inside score_Text
    }
    else if(userScore > 1){ // if user scored more than 1
        let scoreTag = '<span>and nice ????, You got <p>'+ userScore +'</p> out of <p>'+ questions.length +'</p></span>';
        scoreText.innerHTML = scoreTag;
    }
    else{ // if user scored less than 1
        let scoreTag = '<span>and sorry ????, You got only <p>'+ userScore +'</p> out of <p>'+ questions.length +'</p></span>';
        scoreText.innerHTML = scoreTag;
    }
}

function startTimer(time){
    counter = setInterval(timer, 1000);
    function timer(){
        timeCount.textContent = time; //changing the value of timeCount with time value
        time--; //decrement the time value
        if(time < 9){ //if timer is less than 9
            let addZero = timeCount.textContent; 
            timeCount.textContent = "0" + addZero; //add a 0 before time value
        }
        if(time < 0){ //if timer is less than 0
            clearInterval(counter); //clear counter
            timeText.textContent = "Time Off"; //change the time text to time off
            const allOptions = option_list.children.length; //getting all option items
            let correcAns = questions[que_count].answer; //getting correct answer from array
            for(i=0; i < allOptions; i++){
                if(option_list.children[i].textContent == correcAns){ //if there is an option which is matched to an array answer
                    option_list.children[i].setAttribute("class", "option correct"); //adding green color to matched option
                    option_list.children[i].insertAdjacentHTML("beforeend", tickIconTag); //adding tick icon to matched option
                    console.log("Time Off: Auto selected correct answer.");
                }
            }
            for(i=0; i < allOptions; i++){
                option_list.children[i].classList.add("disabled"); //once user select an option then disabled all options
            }
            next_btn.classList.add("show"); //show the next button if user selected any option
        }
    }
}

function startTimerLine(time){
    counterLine = setInterval(timer, 29);
    function timer(){
        time += 1; //upgrading time value with 1
        time_line.style.width = time + "px"; //increasing width of time_line with px by time value
        if(time > 549){ //if time value is greater than 549
            clearInterval(counterLine); //clear counterLine
        }
    }
}

function queCounter(index){
    //creating a new span tag and passing the question number and total question
    let totalQueCounTag = '<span><p>'+ index +'</p> of <p>'+ questions.length +'</p> Questions</span>';
    bottom_ques_counter.innerHTML = totalQueCounTag;  //adding new span tag inside bottom_ques_counter
}

 


Bài 15: Javascript Turorial App - Budget App

Chưa có bình luận 1164
Javascript Cơ Bản, Javascript App, Web Javascript, Học Javascript, Học Js Cơ Bản, Javascript Kết Hợp Api, Javascript Với Api, Api App, Học Cơ Bản Js, Học Cơ Bản Javascript, Javascipt Covid, Covid Tracker Js, Website Với Javacript, Javacript Là Gì, Javascipt Api, Ja,

Javascript Turorial App - Viết ứng dụng tính toán ngân sách thu chi

Javascript Turorial App - Viết ứng dụng tính toán ngân sách thu chi

File index.html

<!DOCTYPE html>
<html lang="en">

<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <!-- bootstrap css -->
 <link rel="stylesheet" href="css/bootstrap.min.css">
 <!-- main css -->
 <link rel="stylesheet" href="css/main.css">
 <!-- google fonts -->
 <link href="https://fonts.googleapis.com/css?family=Courgette" rel="stylesheet">

 <!-- font awesome -->
 <link rel="stylesheet" href="css/all.css">
 <title>budget app</title>
 <style>
 </style>
</head>

<body>
 <div class="container-fluid">
  <div class="row">
   <div class="col-11 mx-auto pt-3">
    <!-- title -->
    <h3 class="text-uppercase mb-4">budget app</h3>
    <div class="row">
     <div class="col-md-5 my-3">
      <!-- budget feedback -->
      <div class="budget-feedback alert alert-danger text-capitalize">budget feedback</div>
      <!-- budget form -->
      <form id="budget-form" class=" budget-form">
       <h5 class="text-capitalize">please enter your budget</h5>
       <div class="form-group">
        <input type="number" class="form-control budget-input" id="budget-input">
       </div>
       <!-- submit button -->
       <button type="submit" class="btn text-capitalize budget-submit" id="budget-submit">calculate</button>
      </form>
     </div>
     <div class="col-md-7">
      <!-- app info -->
      <div class="row my-3">
       <div class="col-4 text-center mb-2">
        <h6 class="text-uppercase info-title">budget</h6>
        <span class="budget-icon"><i class="fas fa-money-bill-alt"></i></span>
        <h4 class="text-uppercase mt-2 budget" id="budget"><span>$ </span><span id="budget-amount">0</span></h4>
       </div>
       <div class="col-4 text-center">
        <h6 class="text-uppercase info-title">expenses</h6>
        <span class="expense-icon"><i class="far fa-credit-card"></i></span>
        <h4 class="text-uppercase mt-2 expense" id="expense"><span>$ </span><span id="expense-amount">0</span></h4>
       </div>
       <div class="col-4 text-center">
        <h6 class="text-uppercase info-title">balance</h6>
        <span class="balance-icon"><i class="fas fa-dollar-sign"></i></span>
        <h4 class="text-uppercase mt-2 balance" id="balance"> <span>$ </span><span id="balance-amount">0</span></h4>
       </div>
      </div>
     </div>
    </div>

    <div class="row">
     <div class="col-md-5 my-3">
      <!-- expense feedback -->
      <div class="expense-feedback alert alert-danger text-capitalize">expense feedback</div>
      <!-- expense form -->
      <form id="expense-form" class=" expense-form">
       <h5 class="text-capitalize">please enter your expense</h5>
       <div class="form-group">
        <input type="text" class="form-control expense-input" id="expense-input">
       </div>
       <h5 class="text-capitalize">please enter expense amount</h5>
       <div class="form-group">
        <input type="number" class="form-control expense-input" id="amount-input">
       </div>
       <!-- submit button -->
       <button type="submit" class="btn text-capitalize expense-submit" id="expense-submit">add expense</button>
      </form>
     </div>
     <div class="col-md-7 my-3">
      <!-- expense list -->
      <div class="expense-list" id="expense-list">

       <div class="expense-list__info d-flex justify-content-between text-capitalize">
        <h5 class="list-item">expense title</h5>
        <h5 class="list-item">expense value</h5>
        <h5 class="list-item"></h5>
       </div>
       <!-- single expense -->

       <!-- <div class="expense">
        <div class="expense-item d-flex justify-content-between align-items-baseline">

         <h6 class="expense-title mb-0 text-uppercase list-item">- title</h6>
         <h5 class="expense-amount mb-0 list-item">amount</h5>

         <div class="expense-icons list-item">

          <a href="#" class="edit-icon mx-2" data-id="${expense.id}">
           <i class="fas fa-edit"></i>
          </a>
          <a href="#" class="delete-icon" data-id="${expense.id}">
           <i class="fas fa-trash"></i>
          </a>
         </div>
        </div>

       </div> -->

       <!-- end of single expense -->

      </div>
     </div>
    </div>

   </div>
  </div>
 </div>

 <!-- jquery -->
 <script src="js/jquery-3.3.1.min.js"></script>
 <!-- bootstrap js -->
 <script src="js/bootstrap.bundle.min.js"></script>
 <!-- script js -->
 <script src="js/app.js"></script>
</body>

</html>

File main.css

:root {
  --mainWhite: #f5f5f5f5;
  --mainDark: #333333;
  --mainGreen: #317b22;
  --mainRed: #b80c09;
  --mainBlue: #05668d;
}

body {
  background: var(--mainWhite);
  color: var(--mainDark);
}
.budget-feedback,
.expense-feedback {
  display: none;
}

.budget-form {
  border: 0.15rem solid var(--mainGreen);
  padding: 1rem;
  border-radius: 0.25rem;
}
.expense-form {
  border: 0.15rem solid var(--mainRed);
  padding: 1rem;
  border-radius: 0.25rem;
}
.budget-submit {
  background: transparent;
  border: 0.1rem solid var(--mainGreen);
  color: var(--mainGreen);
}
.expense-submit {
  background: transparent;
  border: 0.1rem solid var(--mainRed);
  color: var(--mainRed);
}
.expense-submit:hover {
  background: var(--mainRed);
  color: var(--mainWhite);
}
.budget-submit:hover {
  background: var(--mainGreen);
  color: var(--mainDark);
}

.budget-input {
  border: 0.05rem solid var(--mainGreen) !important;
}
.expense-input {
  border: 0.05rem solid var(--mainRed) !important;
}
.expense-amount,
.expense-title {
  color: var(--mainRed);
}
.edit-icon {
  color: var(--mainBlue);
  cursor: pointer;
  font-size: 1rem;
  text-decoration: none !important;
}
.delete-icon {
  color: var(--mainRed);
  cursor: pointer;
  font-size: 1rem;
  text-decoration: none !important;
}
.edit-icon:hover {
  color: var(--mainBlue);
}
.delete-icon:hover {
  color: var(--mainRed);
}
.showItem {
  display: block;
}
.info-title {
  font-size: 1.5rem;
}
.budget {
  font-size: 1.6rem;
  color: var(--mainGreen);
}
.expense {
  font-size: 1.6rem;
  color: var(--mainRed);
}
.balance {
  font-size: 1.6rem;
}
.budget-icon,
.expense-icon,
.balance-icon {
  font-size: 2.5rem;
  color: var(--mainBlue);
}
.showRed {
  color: var(--mainRed);
}
.showGreen {
  color: var(--mainGreen);
}
.showBlack {
  color: var(--mainDark);
}
@media screen and (min-width: 992px) {
  .budget {
    font-size: 2.6rem;
    color: var(--mainGreen);
  }
  .expense {
    font-size: 2.6rem;
    color: var(--mainRed);
  }
  .balance {
    font-size: 2.6rem;
  }
  .budget-icon,
  .expense-icon,
  .balance-icon {
    font-size: 3.5rem;
    color: var(--mainBlue);
  }
}
.list-item {
  flex: 0 0 33.33%;
  text-align: center;
}
.expense-item {
  height: 2rem;
}

File app.js

class UI {
  constructor() {
    this.budgetFeedback = document.querySelector(".budget-feedback");
    this.expenseFeedback = document.querySelector(".expense-feedback");
    this.budgetForm = document.getElementById("budget-form");
    this.budgetInput = document.getElementById("budget-input");
    this.budgetAmount = document.getElementById("budget-amount");
    this.expenseAmount = document.getElementById("expense-amount");
    this.balance = document.getElementById("balance");
    this.balanceAmount = document.getElementById("balance-amount");
    this.expenseForm = document.getElementById("expense-form");
    this.expenseInput = document.getElementById("expense-input");
    this.amountInput = document.getElementById("amount-input");
    this.expenseList = document.getElementById("expense-list");
    this.itemList = [];
    this.itemID = 0;
  }
}

 

 


Bài 16: Javascript Turorial App - Voice Chat

Chưa có bình luận 1320
Javascript Cơ Bản, Javascript App, Web Javascript, Học Javascript, Học Js Cơ Bản, Javascript Kết Hợp Api, Javascript Với Api, Api App, Học Cơ Bản Js, Học Cơ Bản Javascript, Javascipt Covid, Covid Tracker Js, Website Với Javacript, Javacript Là Gì, Javascipt Api, Ja,

Javascript Turorial App - Viết ứng dụng chat voice JS

Javascript Turorial App - Viết ứng dụng chat voice JS

File index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <header>Chat with Chitti</header>
    <section class="main">
            <div class="user-area">
                <img src="images/user.png">
            </div>
            <div class="chatarea-main">
                <div class="chatarea-outer">
                    <!-- <div class="chatarea-inner user">Hello hi, how area you, i am good. What about you!</div>
                    <div class="chatarea-inner chatbot">Hello hi, how area you, i am good. What about you!</div>
                    <div class="chatarea-inner user">Hello hi, how area you, i am good. What about you!</div> -->
                </div>
            </div>    
            <div class="chatbot-area">
                <img src="images/chatbot.png">
            </div>
        <button id="mic"><i class="flaticon-microphone"></i></button>
    </section>
    <script src="js/main.js"></script>
</body>
</html>

File style.css

@font-face {
	font-family: 'Roboto-Regular';
	src: url('../fonts/Roboto-Regular.eot');
	src: local('☺'), url('../fonts/Roboto-Regular.woff') format('woff'), url('../fonts/Roboto-Regular.ttf') format('truetype'), url('../fonts/Roboto-Regular.svg') format('svg');
	font-weight: normal;
	font-style: normal;
}

@font-face {
    font-family: "Flaticon";
    src: url("../fonts/Flaticon.eot");
    src: url("../fonts/Flaticon.eot?#iefix") format("embedded-opentype"),
         url("../fonts/Flaticon.woff2") format("woff2"),
         url("../fonts/Flaticon.woff") format("woff"),
         url("../fonts/Flaticon.ttf") format("truetype"),
         url("../fonts/Flaticon.svg#Flaticon") format("svg");
    font-weight: normal;
    font-style: normal;
  }
  
  @media screen and (-webkit-min-device-pixel-ratio:0) {
    @font-face {
      font-family: "Flaticon";
      src: url("../fonts/Flaticon.svg#Flaticon") format("svg");
    }
  }
  
  [class^="flaticon-"]:before, [class*=" flaticon-"]:before,
  [class^="flaticon-"]:after, [class*=" flaticon-"]:after {   
    font-family: Flaticon;
          font-size: 30px;
  font-style: normal;
  }
  
.flaticon-microphone:before { content: "\f100"; }

*{margin: 0;padding: 0;box-sizing: border-box;}
body{font-family: 'Roboto-Regular';background: #E7F2F1;}
header {
    height: 60px;
    background: #fff;
    color: #03283B;
    text-align: center;
    line-height: 60px;
    font-size: 30px;
    box-shadow: 10px 0 5px #b9b7b7;
    width: 100%;
    position: fixed;
    z-index: 2;
}
.main {
    width: 100%;
    float: left;
    margin-top: 60px;
    padding: 30px 0;
}
.main button {
    background: #ff3b3b;
    padding: 15px;
    border-radius: 50%;
    box-shadow: 0 0 10px #666;
    position: fixed;
    right: 20px;
    bottom: 20px;
    border: none;
    color: #fff;
    cursor: pointer;
}
.main button:focus{outline: none;}
.container {
    width: 85%;
    margin: 0 auto;
}
.user-area, .chatbot-area {
    width: 20%;
    height: calc(100vh - 60px);
    margin-right: 15px;
    display: flex;
    align-items: center;
    position: fixed;
    left: 80px;
    z-index: 99999;
}
.chatbot-area {
    float: right;
    right: 80px;
    left: auto;
}
.user-area img, .chatbot-area img {
    width: 100%;
}
.user-area img{left: 0;}
.chatarea-main {
    width: 42%;
    margin: 0 auto;
}
.chatarea-outer {
    width: 100%;
    float: left;
}
.chatbot-area .chatarea-main{float: left;}
.chatarea.user {
    float: right;
    width: 40%;
    padding: 20px 0;
}

.chatarea-inner {
    float: left;
    width: 60%;
    padding: 10px;
    color: #fff;
    position: relative;
    margin: 5px 0;
}
.chatarea-inner.user{
    background: #6522A4;
}
.chatarea-inner.chatbot{
    background: #466EB6;
    float: right;
}
.chatarea-inner.user:before {
    content: '';
    position: absolute;
    border-right: 20px solid #6522A4;
    border-top: 20px solid transparent;
    border-bottom: 0px solid transparent;
    bottom: 0;
    left: -20px;
}
.chatarea-inner.chatbot:before {
    content: '';
    position: absolute;
    border-left: 20px solid #466EB6;
    border-top: 20px solid transparent;
    border-bottom: 0px solid transparent;
    bottom: 0;
    right: -20px;
}

.chatbot-area .chatarea-inner{float: left;}

File main.js

let mic = document.getElementById("mic");
let chatareamain = document.querySelector('.chatarea-main');
let chatareaouter = document.querySelector('.chatarea-outer');

let intro = ["Hello, I am Chitti", "Hi, I am a Robo", "Hello, My name is Chitti"];
let help = ["How may i assist you?","How can i help you?","What i can do for you?"];
let greetings = ["i am good you little piece of love", "i am fine, what about you", "don't want to talk", "i am good"];
let hobbies = ["i love to talk with humans", "i like to make friends like you", "i like cooking"];
let pizzas = ["which type of pizza do you like?", "i can make a pizza for you", "i would love to make a pizza for you", "would you like cheese pizza?"];
let thank = ["Most welcome","Not an issue","Its my pleasure","Mention not"];
let closing = ['Ok bye-bye','As you wish, bye take-care','Bye-bye, see you soon..']

const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
const recognition = new SpeechRecognition();

function showusermsg(usermsg){
    let output = '';
    output += `<div class="chatarea-inner user">${usermsg}</div>`;
    chatareaouter.innerHTML += output;
    return chatareaouter;
}

function showchatbotmsg(chatbotmsg){
    let output = '';
    output += `<div class="chatarea-inner chatbot">${chatbotmsg}</div>`;
    chatareaouter.innerHTML += output;
    return chatareaouter;
}

function chatbotvoice(message){
    const speech = new SpeechSynthesisUtterance();
    speech.text = "This is test message";
    if(message.includes('who are you')){
        let finalresult = intro[Math.floor(Math.random() * intro.length)];
        speech.text = finalresult;
    }
    if(message.includes('fine')){
        let finalresult = help[Math.floor(Math.random() * help.length)];
        speech.text = finalresult;
    }
    if(message.includes('how are you' || 'how are you doing today')){
        let finalresult = greetings[Math.floor(Math.random() * greetings.length)];
        speech.text = finalresult;
    }
    if(message.includes('tell me something about you' || 'tell me something about your hobbies')){
        let finalresult = hobbies[Math.floor(Math.random() * hobbies.length)];
        speech.text = finalresult;
    }
    if(message.includes('pizza')){
        let finalresult = pizzas[Math.floor(Math.random() * pizzas.length)];
        speech.text = finalresult;
    }
    if(message.includes('thank you' || 'thank you so much')){
        let finalresult = thank[Math.floor(Math.random() * thank.length)];
        speech.text = finalresult;
    }
    if(message.includes('talk to you' || 'talk')){
        let finalresult = closing[Math.floor(Math.random() * closing.length)];
        speech.text = finalresult;
    }
    window.speechSynthesis.speak(speech);
    chatareamain.appendChild(showchatbotmsg(speech.text));
}

recognition.onresult=function(e){
    let resultIndex = e.resultIndex;
    let transcript = e.results[resultIndex][0].transcript;
    chatareamain.appendChild(showusermsg(transcript));
    chatbotvoice(transcript);
    console.log(transcript);
}
recognition.onend=function(){
    mic.style.background="#ff3b3b";
}
mic.addEventListener("click", function(){
    mic.style.background='#39c81f';
    recognition.start();
    console.log("Activated");
})

 


Bài 17: Javascript Turorial App - Simple Calculator App

Chưa có bình luận 1151
Javascript Cơ Bản, Javascript App, Web Javascript, Học Javascript, Học Js Cơ Bản, Javascript Kết Hợp Api, Javascript Với Api, Api App, Học Cơ Bản Js, Học Cơ Bản Javascript, Javascipt Covid, Covid Tracker Js, Website Với Javacript, Javacript Là Gì, Javascipt Api, Ja,

Javascript Turorial App - Viết ứng dụng máy tính cầm tay đơn giản bằng JS

 

File index.html

<html>
	<head>
		<link rel="stylesheet" type="text/css" href="style.css">
		<link href="https://fonts.googleapis.com/css?family=Open+Sans:600,700" rel="stylesheet">
		<title>A simple calculator</title>
	</head>
	<body>
		<div id="container">
			<div id="calculator">
				<div id="result">
					<div id="history">
						<p id="history-value"></p>
					</div>
					<div id="output">
						<p id="output-value"></p>
					</div>
				</div>
				<div id="keyboard">
					<button class="operator" id="clear">C</button>
					<button class="operator" id="backspace">CE</button>
					<button class="operator" id="%">%</button>
					<button class="operator" id="/">&#247;</button>
					<button class="number" id="7">7</button>
					<button class="number" id="8">8</button>
					<button class="number" id="9">9</button>
					<button class="operator" id="*">&times;</button>
					<button class="number" id="4">4</button>
					<button class="number" id="5">5</button>
					<button class="number" id="6">6</button>
					<button class="operator" id="-">-</button>
					<button class="number" id="1">1</button>
					<button class="number" id="2">2</button>
					<button class="number" id="3">3</button>
					<button class="operator" id="+">+</button>
					<button class="empty" id="empty"></button>
					<button class="number" id="0">0</button>
					<button class="empty" id="empty"></button>
					<button class="operator" id="=">=</button>
				</div>
			</div>
		</div>
		<script src="script.js"></script>
	</body>
</html>

File style.css

body{
	font-family: 'Open Sans',sans-serif;
	background-color: black;
}
#container{
	width: 1000px;
	height: 550px;
	background-image: linear-gradient(rgba(0,0,0,0.3),rgba(0,0,0,0.3)), url(bgImg.jpg);
	margin: 20px auto;	
}
#calculator{
	width: 320px;
	height: 520px;
	background-color: #eaedef;
	margin: 0 auto;
	top: 20px;
	position: relative;
	border-radius: 5px;
	box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}
#result{
	height: 120px;
}
#history{
	text-align: right;
	height: 20px;
	margin: 0 20px;
	padding-top: 20px;
	font-size: 15px;
	color: #919191;
}
#output{
	text-align: right;
	height: 60px;
	margin: 10px 20px;
	font-size: 30px;
}
#keyboard{
	height: 400px;
}
.operator, .number, .empty{
	width: 50px;
	height: 50px;
	margin: 15px;
	float: left;
	border-radius: 50%;
	border-width: 0;
	font-weight: bold;
	font-size: 15px;
}
.number, .empty{
	background-color: #eaedef;
}
.number, .operator{
	cursor: pointer;
}
.operator:active, .number:active{
	font-size: 13px;
}
.operator:focus, .number:focus, .empty:focus{
	outline: 0;
}
button:nth-child(4){
	font-size: 20px;
	background-color: #20b2aa;
}
button:nth-child(8){
	font-size: 20px;
	background-color: #ffa500;
}
button:nth-child(12){
	font-size: 20px;
	background-color: #f08080;
}
button:nth-child(16){
	font-size: 20px;
	background-color: #7d93e0;
}
button:nth-child(20){
	font-size: 20px;
	background-color: #9477af;
}

File script.js

function getHistory(){
	return document.getElementById("history-value").innerText;
}
function printHistory(num){
	document.getElementById("history-value").innerText=num;
}
function getOutput(){
	return document.getElementById("output-value").innerText;
}
function printOutput(num){
	if(num==""){
		document.getElementById("output-value").innerText=num;
	}
	else{
		document.getElementById("output-value").innerText=getFormattedNumber(num);
	}	
}
function getFormattedNumber(num){
	if(num=="-"){
		return "";
	}
	var n = Number(num);
	var value = n.toLocaleString("en");
	return value;
}
function reverseNumberFormat(num){
	return Number(num.replace(/,/g,''));
}
var operator = document.getElementsByClassName("operator");
for(var i =0;i<operator.length;i++){
	operator[i].addEventListener('click',function(){
		if(this.id=="clear"){
			printHistory("");
			printOutput("");
		}
		else if(this.id=="backspace"){
			var output=reverseNumberFormat(getOutput()).toString();
			if(output){//if output has a value
				output= output.substr(0,output.length-1);
				printOutput(output);
			}
		}
		else{
			var output=getOutput();
			var history=getHistory();
			if(output==""&&history!=""){
				if(isNaN(history[history.length-1])){
					history= history.substr(0,history.length-1);
				}
			}
			if(output!="" || history!=""){
				output= output==""?output:reverseNumberFormat(output);
				history=history+output;
				if(this.id=="="){
					var result=eval(history);
					printOutput(result);
					printHistory("");
				}
				else{
					history=history+this.id;
					printHistory(history);
					printOutput("");
				}
			}
		}
		
	});
}
var number = document.getElementsByClassName("number");
for(var i =0;i<number.length;i++){
	number[i].addEventListener('click',function(){
		var output=reverseNumberFormat(getOutput());
		if(output!=NaN){ //if output is a number
			output=output+this.id;
			printOutput(output);
		}
	});
}

 


Bài 18: Javascript Turorial App - Weight Converter App

Chưa có bình luận 918
Javascript Cơ Bản, Javascript App, Web Javascript, Học Javascript, Học Js Cơ Bản, Javascript Kết Hợp Api, Javascript Với Api, Api App, Học Cơ Bản Js, Học Cơ Bản Javascript, Javascipt Covid, Covid Tracker Js, Website Với Javacript, Javacript Là Gì, Javascipt Api, Ja,

Javascript Turorial App - Viết ứng dụng chuyển đổi đơn vị cân nặng pounds

Javascript Turorial App - Viết ứng dụng chuyển đổi đơn vị cân nặng pounds

File index.html

<html>
	<head>
		<link rel="stylesheet" type="text/css" href="style.css">
		<link href="https://fonts.googleapis.com/css?family=Open+Sans:600,700" rel="stylesheet">
		<title>Weight Converter</title>
<style>
body{
  margin-top:70px;
  background:#333;
  color:#fff;
}
</style>
	</head>
	<body>
		<div class="container">
  <div class="row">
    <div class="col-md-6 offset-md-3">
      <h1 class="display-4 text-center mb-3">Weight Converter</h1>
      <form>
        <div class="form-group">
          <input id="lbsInput" type="number" class="form-control form-control-lg" placeholder="Enter Pounds...">
        </div>
      </form>
      <div id="output">
        <div class="card card-primary mb-2">
          <div class="card-block">
            <h4>Grams:</h4>
            <div id="gramsOutput"></div>
          </div>
        </div>

        <div class="card card-success mb-2">
          <div class="card-block">
            <h4>Kilograms:</h4>
            <div id="kgOutput"></div>
          </div>
        </div>

        <div class="card card-danger mb-2">
          <div class="card-block">
            <h4>Ounces:</h4>
            <div id="ozOutput"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
		<script src="script.js"></script>
	</body>
</html>

File App.js

document.getElementById("output").style.visibility = "hidden";
document.getElementById("lbsInput").addEventListener("input", function(e) {
  document.getElementById("output").style.visibility = "visible";
  let lbs = e.target.value;
  document.getElementById("gramsOutput").innerHTML = lbs / 0.0022046;
  document.getElementById("kgOutput").innerHTML = lbs / 2.2046;
  document.getElementById("ozOutput").innerHTML = lbs * 16;
});

 

 


Bài 19: Javascript Tutorial App - BMI calculator App

Chưa có bình luận 2712
Javascript Cơ Bản, Javascript App, Web Javascript, Học Javascript, Học Js Cơ Bản, Javascript Kết Hợp Api, Javascript Với Api, Api App, Học Cơ Bản Js, Học Cơ Bản Javascript, Javascipt Covid, Covid Tracker Js, Website Với Javacript, Javacript Là Gì, Javascipt Api, Ja,

Javascript Tutorial App - Viết ứng dụng tính chỉ số cơ thể BMI bằng JS

Javascript Tutorial App - Viết ứng dụng tính chỉ số cơ thể BMI bằng JS

File index.html

<!DOCTYPE html>
<html>
	<head>
		<title>JavaScript: BMI calculator</title>
	</head>
<style>
body {
    background-color: #effffe;
    text-align: center;
    margin-top: 45px;
    font-family: monospace, sans-serif;
    font-size: 15px;
    font-weight: bold;
}

.values {
    width: 100px;
    margin-right: 4px;
}
#num1 {
    margin-left: 2px;
}

.firstLabel {
    margin-left: -5px;
}

#gender {
    margin-left: -5px;
}
#btn {
    border: solid #000 2px;
    border-radius: 25%;
}
#btn:hover {
    background-color: #fefecc;
    font-weight: bold;
}
h4 {
    padding-top: 25px;
}

#result {
    border: solid #ccc 2px;
    border-radius: 25%;
    width:150px;
    padding-top: 10px;
    position: relative;
    left: 23%;
    height:40px;
    margin: 20px;
    text-align: center;
    background-color: #fff;
    font-size: 20px;
}
#calc {
    border: solid #000 3px;
    width: 350px;
    height: 350px;
    border-radius: 8%;
    text-align: center;
    padding: 15px;
    padding-top: 35px;
    padding-bottom: 35px;
    position: absolute;
    top: 18%;
    left:36%;
    background-color: #ff901a;
}

#message {
    font-weight: bold;
    font-size: 20px;
    text-transform: uppercase;
}

@media (max-width:815px){
    
    #calc {
       position: relative;
       width: 50%;
       margin-left:-70px; 
       padding-bottom: 55px;
    }
    
    #result {
        position: relative;
        width: 34%;
        left: 22%;
    }    
    
    #radio {
        position: relative;
        width: 78%;
    }
    #num1 {
        margin-left: -3px;
        margin-right: 4px;
    }
    #num2 {
        margin-left: -6px;
        margin-right: 6px;
    }
    .secondLabel{
        margin-left: 90px;
    }
}
</style>
<body>
	<h1>BMI calculator</h1>
<form id="calc">
	<div class="firstLabel">
	<label>Your height: </label>
		<input class = "values" type="text"  id="num1" required><label class="secondLabel">centimetres</label>
	</div>
		<br>
	<div>
		<label>Your weight:</label>
		<input class = "values" type="text" id="num2" required ><label class="secondLabel">kilogrammes</label>
	</div>
		<br>
	<div id="gender">
	<input  name="gender" type="radio" value="0" checked>	
	<label>Female</label>
	<input name="gender" type="radio" value="1">
	<label>Male</label>
	</div>
    <br>
	<button id="btn" type="submit" class="btn btn-primary" >Calculate</button>
	<div>
		<h4>Your BMI:</h4>
		<p id="result"></p>
	</div>
	<br>
	<p id="message"></p>
	</form>
  <script type="text/javascript" src="app.js"></script>
	</body>
</html>

File app.js

document.getElementById("calc").addEventListener("submit", calculate); 	
	
function calculate(e){
var radios = document.getElementsByName('gender');
var height = Number(document.getElementById("num1").value);
var weight = Number(document.getElementById("num2").value);
var height2 = height * height;
var bmi = (weight / height2)*10000;	
		e.preventDefault();
		document.getElementById("result").innerHTML = bmi.toFixed(2);
	for (var i = 0, length = radios.length; i < length; i++)
{
 if (radios[i].checked)
 {
    break;
 }
}
if (radios[i].value == 0){
	  
  if(bmi <= 18.5) {
		document.getElementById("message").innerHTML = "Underweight!";
	 return;
	}
		else if (bmi <= 24.9) {
		document.getElementById("message").innerHTML = "Normal weight!";
	return;
	}
	
  else if (bmi <= 27.3) {
		document.getElementById("message").innerHTML = "Slightly overweight!";
	return;
	}
	
  else if (bmi <= 32.3) {
		document.getElementById("message").innerHTML = "Overweight!";
	return;
	}
	
  else if (bmi <= 45.0) {
		document.getElementById("message").innerHTML = "Obese!";
	return;
	}
	
  else if (bmi => 45.1) {
	    document.getElementById("message").innerHTML = "Extremely obese!";
	return;
	} 
  }
	else{
			if (bmi <= 20.5) {
		document.getElementById("message").innerHTML = "Underweight!";
	 return;
	}
   else if (bmi <= 25.9) {
		document.getElementById("message").innerHTML = "Normal weight!";
	return;
	}
	
   else if (bmi <= 29.3) {
		document.getElementById("message").innerHTML = "Slightly overweight!";
	return;
	}
	
   else if (bmi <= 34.3) {
		document.getElementById("message").innerHTML = "Overweight!";
	return;
	}
	
  else if (bmi <= 45.0) {
		document.getElementById("message").innerHTML = "Obese!";
	return;
	}
	
  else if (bmi => 45.1) {
	    document.getElementById("message").innerHTML = "Extremely obese!";
	return;
	} 		
 }
}

 

 


Bài 20: Javascript Turorial App - Caro game App

Chưa có bình luận 1180
Javascript Cơ Bản, Javascript App, Web Javascript, Học Javascript, Học Js Cơ Bản, Javascript Kết Hợp Api, Javascript Với Api, Api App, Học Cơ Bản Js, Học Cơ Bản Javascript, Javascipt Covid, Covid Tracker Js, Website Với Javacript, Javacript Là Gì, Javascipt Api, Ja,

Javascript Turorial App - Viết ứng dụng chơi game cờ caro bằng JS

Javascript Turorial App - Viết ứng dụng chơi game cờ caro bằng JS

 

File index.html

<html>
	<head>
		<link rel="stylesheet" type="text/css" href="style.css">
		<link href="https://fonts.googleapis.com/css?family=Open+Sans:600,700" rel="stylesheet">
		<title>Caro App</title>
<style>
@import url('https://fonts.googleapis.com/css?family=Bubbler+One|Lato:400,900');

/* BASIC RESET AND SETUP */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  background-color: #E0DDBC;
}

/* ============= */
/* TITLE STYLING */
.title-box {
  margin: 10px auto;
  width: 300px;
  border-bottom: 2px solid black;
}

.title-box h1 {
  text-align: center;
  font: 60px 'Bubbler One', sans-serif;
}

/* ============= */
/* BOARD STYLING */
.container {
  padding: 20px;
  width: 360px;
  margin: 10px auto;
  border-radius: 23px;
}

.game-panel {
  /* clear float */
  overflow: hidden;
  height: auto;
  width: 300px;
  margin: auto;
}

/* board colour */
.container,
.game-panel span {
  background-color: #3581B8;
}

.game-panel span {
  float: left;
  width: 100px;
  height: 100px;
  cursor: pointer;
  font: 400 80px 'Lato', sans-serif;
  line-height: 90px;
  text-align: center;
  color: #92D5DD;
}

#box-0, #box-3, #box-6 {
  border-right: 4px solid #92D5DD;
}

#box-2, #box-5, #box-8 {
  border-left: 4px solid #92D5DD;
}

#box-3, #box-4, #box-5 {
  border-top: 4px solid #92D5DD;
  border-bottom: 4px solid #92D5DD;
}

/* ===================== */
/* CONTROL PANEL STYLING */
.control-panel,
.reset-area,
.control-panel h3 {
  background-color: #3581B8;
}

.control-panel {
  width: 360px;
  padding: 15px;
  margin-left: auto;
  margin-right: auto;
  margin-top: 15px;
  border-radius: 23px;
  color: #92D5DD;
}

.control-panel h3 {
  text-align: center;
  margin-top: -5px;
  margin-bottom: 10px;
  font: 900 25px 'Lato', sans-serif;
}

/* general buttons styling */
button {
  border: 0;
  border-radius: 10px;
  position: relative;
  background-color: #F9A03F;
  box-shadow: 0px 6px #B7752D;
  cursor: pointer;
}

button:active {
  top: 4px;
  background-color: #E28A2B;
  box-shadow: 0px 2px #B7752D;
}

button:focus {
  outline: 0;
}

/* X - O buttons styling */
#choose-x, #choose-o {
  height: 60px;
  width: 110px;
  margin-bottom: 20px;
  font: 400 24px 'Lato', sans-serif;
  color: black;
}

#choose-x {
  margin-left: 15px;
}

#choose-o {
  margin-left: 75px;
}

.active {
  top: 4px;
  background-color: #E28A2B;
  box-shadow: 0px 2px #B7752D;
  cursor: default;
}

/* Start/Reset buttons styling */
#reset {
  height: 60px;
  width: 200px;
  margin-left: 60px;
  font: 400 18px 'Lato', sans-serif;
}

/* ===================== */
/* SIGNATURE STYLING */
p {
  margin-top: 30px;
  margin-bottom: 10px;
  padding-top: 5px;
  text-align: center;
  font: 16px 'Bubbler One', sans-serif;
  border-top: 1px solid black;
}

/* ===================== */
/* WINNING (or LOSING or DRAWING) MESSAGE */
.overlay {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100%;
  width: 100%;
  transition: 0.8s ease;
  background-color: #3581B8;
  cursor: pointer;
}

.message {
  color: #FB3640;
  position: absolute;
  top: 40%;
  left: 50%;
  font: 400 40px 'Lato', sans-serif;
  background-color: #3581B8;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
}
</style>
	</head>
	<body>
		<div id="container">
			<div class="title-box">
  <h1>TIC-TAC-TOE</h1>
</div>

<div class="container">
  <div class="game-panel">
    <span id="box-0"></span>
    <span id="box-1"></span>
    <span id="box-2"></span>
    <span id="box-3"></span>
    <span id="box-4"></span>
    <span id="box-5"></span>
    <span id="box-6"></span>
    <span id="box-7"></span>
    <span id="box-8"></span>
  </div>
</div>

<div class="control-panel">
  <h3>C O N T R O L &nbsp;&nbsp; P A N E L</h3>
  <button id="choose-x" class="active" disabled>X</button>
  <button id="choose-o">O</button>
  <div class="reset-area">
    <button id="reset">START/RESET</button>
  </div>
</div> 

<div class="overlay">
  <div class="message"></div>
</div>

<p>Designed & Coded in Brighton<br>by Arry Tapiheroe</p>
		</div>
		<script src="script.js"></script>
	</body>
</html>

 

File app.js

// Javascript Tic Tac Toe App
// A project for FreeCodeCamp Front End Certification
// Designed and Coded in Brighton, Sussex, (pre-Brexit) England
// by Arry Tapiheroe

// I've lost (or, effectively utilised) many lunch times and post-dinner times in the coding of this app

// jQuery used when necessary

// initial game starts with player starting with "X"
var game = {
  player: "X",
  computer: "O",
  turn: "player",
  moves: 0,
  over: false
};

// create the board as an array
//  0 | 1 | 2
//  ---------
//  3 | 4 | 5
//  ---------
//  6 | 7 | 8

var board = [0, 0, 0, 
             0, 0, 0, 
             0, 0, 0];

// WIN happens when the sums of either any rows, any columns or any diagonals
// are equal to "-3" for "O" or "3" for "X"
//

// ==================
// PLAYER CLICK BOARD
// ==================
// select the board panels
// add event listener for all the spans
var panels = document.querySelectorAll(".game-panel span");
for (var i = 0; i < panels.length; i++) {
  panels[i].onclick = function(e) {
    if (this.innerHTML == "") {
      this.innerHTML = game.player;
      game.turn = "player";
      if (game.moves == 0) hidePanels();
      game.moves++;
      checkScore();

      if (!game.over) computerMove();
    }
  };
}

// ======================
// COMPUTER MOVE FUNCTION
// ======================
function computerMove() {
  game.turn = "computer";
  if (game.moves == 0) hidePanels();

  daMove();

  game.moves++;
  checkScore();
}

// initial AI is just.. well.. random
// THIS IS NOT AN AI!!
function daMove() {
  var random = Math.floor(Math.random() * 9);
  // recur the function if panel is already filled
  if (panels[random].innerHTML != "") {
    daMove();
  } else {
    panels[random].innerHTML = game.computer;
    return;
  }
}

// ====================
// CHECK SCORE FUNCTION
// ====================
function checkScore() {
  // record the score in the board array
  for (var j = 0; j < panels.length; j++) {
    if (panels[j].innerHTML == "X") board[j] = 1;
    else if (panels[j].innerHTML == "O") board[j] = -1;
  }

  var scoreArray = [
    [board[0], board[1], board[2]],
    [board[3], board[4], board[5]],
    [board[6], board[7], board[8]],
    [board[0], board[3], board[6]],
    [board[1], board[4], board[7]],
    [board[2], board[5], board[8]],
    [board[0], board[4], board[8]],
    [board[2], board[4], board[6]]
  ];

  // go through scoreArray and see if there is a winner
  var sumScore = [];
  for (var k = 0; k < scoreArray.length; k++) {
    sumScore[k] = scoreArray[k].reduce(function(a, b) {
      return a + b;
    }, 0);

    // check if there's a winner
    if (sumScore[k] == -3 || sumScore[k] == 3) {
      game.over = true;
      if (game.turn == "player") {
        endMessage("WIN!");
      } else {
        endMessage("LOSE!");
      }
      return;
    }
  }

  // check if it's a draw
  if (game.moves == 9) {
    game.over = true;
    endMessage("DRAW..");
  }
}

// ==============
// CONTROL PANELS
// ==============
$("#choose-x").on("click", function() {
  game.player = "X";
  game.computer = "O";

  // disable this button (in appearance and class) & enable "O" button
  $(this).prop("disabled", true)
    .toggleClass("active");
  $("#choose-o").prop("disabled", false)
    .toggleClass("active");
});

$("#choose-o").on("click", function() {
  game.player = "O";
  game.computer = "X";

  // disable this button (in appearance and class) & enable "X" button
  $(this).prop("disabled", true)
    .toggleClass("active");
  $("#choose-x").prop("disabled", false)
    .toggleClass("active");
});

// ====================
// START/RESET FUNCTION
// ====================
$("#reset").on("click", function() {
  resetGame();
});

function resetGame() {
  // if game hasn't started
  // button will let computer starts
  if (game.moves == 0) {
    computerMove();
  } else {
    // otherwise
    // reset the game objects
    game.turn = "player";
    game.moves = 0;
    game.over = false;

    // empty the panels
    for (var j = 0; j < panels.length; j++) {
      panels[j].innerHTML = "";
    }

    // show control panel back
    $("#choose-x").slideDown("fast");
    $("#choose-o").slideDown("fast");

    // initialise the score board back
    board = [0, 0, 0, 
             0, 0, 0, 
             0, 0, 0];
  }
}

// ===============
// OTHER FUNCTIONS
// ===============
function hidePanels() {
  $("#choose-x").slideUp("fast");
  $("#choose-o").slideUp("fast");
}

function endMessage(message) {
  $(".message").text(message);
  $(".overlay").fadeTo("fast", 0.9);
}

$(".overlay").click(function() {
  $(this).fadeOut("fast");
  resetGame();
});

 

 


Bài 21: Javascript Turorial App - Shopping Cart App

Chưa có bình luận 1115
Javascript Cơ Bản, Javascript App, Web Javascript, Học Javascript, Học Js Cơ Bản, Javascript Kết Hợp Api, Javascript Với Api, Api App, Học Cơ Bản Js, Học Cơ Bản Javascript, Javascipt Covid, Covid Tracker Js, Website Với Javacript, Javacript Là Gì, Javascipt Api, Ja,

Javascript Turorial App - Viết ứng dụng mua sắm bằng JS

Javascript Turorial App - Viết ứng dụng mua sắm bằng JS

File index.html

<html>
	<head>
		<link rel="stylesheet" type="text/css" href="style.css">
		<link href="https://fonts.googleapis.com/css?family=Open+Sans:600,700" rel="stylesheet">
		<title>Shopping cart App</title>
	</head>
	<body>
		<div id="container">
			<style>

@import url('https://fonts.googleapis.com/css?family=Dancing+Script');
.bodyContainer{
  color: #0D1F4B;
  margin-left: 150px;
  margin-right: 150px;
  margin-top: 50px;
}

.siteName{
  
    font-family: 'Dancing Script', cursive;font-size: 30px;
}

[data-role="navBar"] {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #0D1F4B;
}

[data-role="navItem"] {
    float: left;
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

[data-role="navItem"]:hover{
    background-color: #ED2B68;
    color: white;
    text-decoration: none;
}

h4{
  color: #0095DD;
}

.contShop{
  text-align: right;
  padding-right: 40px;
}

table {
    font-family: arial, sans-serif;
    font-size: medium;
    border-collapse: collapse;
    width: 100%;
}

tr:nth-child(even) {
    background-color: white;
    border: 1px solid #dddddd;
}

tr:nth-child(1) {
  background-color: #0D1F4B;
  color: white;
}

td, th {
    text-align: left;
    padding: 8px;
}

[data-role="qtyValue"]{
  color: #ED2B68;
}

[data-role="price"]{
  padding-top: 15px;
}

button{
  border: none;
  border-radius: 4px;
  background-color: #ED2B68;
  color: white;
  padding: 4px 12px 4px 12px;
}

.button:hover{
  background-color: #0095DD;
}

[data-role="checkout"]{
  background-color: #0095DD;
  font-family: arial, sans-serif;
  font-size: medium;
}

[data-role="cancel"]{
  margin-right: 10px;
  font-size: medium;
}

a{
  color: #ED2B68;
}

ul{
  font-size: 18px;
  list-style: none;
}

[data-role="total"]{
  float: right;
  padding-right: 88px;
}

[data-role="randomButtons"]{
  margin-top: 20px;
  margin-right: 72px;
  float: right;
}
</style>

<ul data-role="navBar">
  <li class="siteName" data-role="navItem">Whitney's Closet</li>
</ul>

<div class="bodyContainer">
<h1>Shopping Cart</h1>

<hr />
<div class="row">
  <div class="col-sm-8"><br>
    <h4>You have <span data-role="qtyValue">0</span> items in your cart.</h4></br>
  </div>
  <div class="col-sm-4 contShop">
    <p><a>Continue shopping</a></div>
</div>

<div class="row">
  <table>
    <tr>
      <th>Product</th>
      <th>Description</th>
      <th>Price</th>
      <th></th>
      <th>Quantity</th>
      <th></th>
      <th>Subtotal</th>
      <th></th>
      <th></th>
    </tr>
    <tr data-role="lineItem">
      <td><img src=""></td>
      <td><select data-role="productsDdl"></select></td>
      <td data-role="price"></td>
      <td>x</td>
      <td><select data-role="qtyDdl"></select></td>
      <td>=</td>
      <td data-role="subtotal"></td>
      <td data-role="addBtn"><button class="button" type="button">Add</button></td>
      <td data-role="removeBtn"><button class="button" type="button">Remove</button></td>
    </tr>
  </table>
  <div><br />

    <h3>Here's What You're Getting!</h3><br />
    <ul class="cartList">
    </ul>

    <br />

    <h4 data-role="total">Total: $<span data-role="totalCost">0</span></h4>
    <br />
    <br />

    <hr />
  <div data-role="randomButtons">
    <button class="button" data-role="cancel" type="button">Cancel</button>
    <button class="button" data-role="checkout" type="button">Check Out</button>
</div>
  </div>
		</div>
		<script src="script.js"></script>
	</body>
</html>

File script.js

$('[data-role="price"]').html("$0");
$('[data-role="subtotal"]').html("$0");

var products = [
{
  title: 'Choose One',
  price: 0.00
}, 
{
  title: 'Blouse',
  price: 60,
  image: "http://www.polyvore.com/cgi/img-thing?.out=jpg&size=l&tid=3024702"
}, 
{
  title: 'Evening Dress',
  price: 110,
  image: "https://s-media-cache-ak0.pinimg.com/236x/21/8c/da/218cdadce9a19122a6fd325fee443efc.jpg"
}, 
{
  title: 'Pants',
  price: 95,
  image: "http://www.polyvore.com/cgi/img-thing?.out=jpg&size=l&tid=126767993"
}, 
{
  title: 'Paris Sweatshirt',
  price: 70,
  image: "https://ae01.alicdn.com/kf/HTB1DplZNpXXXXamaXXXq6xXFXXXB/Modern-Spring-Autumn-and-Winter-Womens-Long-Sleeve-Printed-Pullover-casual-Sweatshirts-Blouse-Tops-Cotton-Eiffel.jpg_220x220.jpg"
}];

function populateProductsDdl(selector, items) {
  var $options = [];

  for (var i = 0; i < items.length; i++) {
    var item = items[i];
    $options.push($('<option />', {
      text: item.title,
      value: /*"$" + */ item.price
    }));
  }
  $(selector).html($options);
}

populateProductsDdl('[data-role="productsDdl"]', products);

//A bad way to load the item's image.
function populateImage(selector){
  if( (selector).text() === products[1].title ){
    $('img').attr('src', "http://www.polyvore.com/cgi/img-thing?.out=jpg&size=l&tid=3024702");
  }
  if( (selector).text() === products[2].title ){
    $('img').attr('src', "https://s-media-cache-ak0.pinimg.com/236x/21/8c/da/218cdadce9a19122a6fd325fee443efc.jpg");
  }
  if( (selector).text() === products[3].title ){
    $('img').attr('src', "http://www.polyvore.com/cgi/img-thing?.out=jpg&size=l&tid=126767993");
  }
  if( (selector).text() === products[4].title ){
    $('img').attr('src', "https://ae01.alicdn.com/kf/HTB1DplZNpXXXXamaXXXq6xXFXXXB/Modern-Spring-Autumn-and-Winter-Womens-Long-Sleeve-Printed-Pullover-casual-Sweatshirts-Blouse-Tops-Cotton-Eiffel.jpg_220x220.jpg");
  }
}

//When a product is selected, populate the price
function populatePrice(selector, priceSelector) {
  var x = $('<p />', {
    text: $(selector).val()
  });
  $(priceSelector).html(x);
}

var qtyOptions = [];

//Set the quantity values in the qty dropdown.
function qtyDdlOptions(someArray, number) {

  for (i = 0; i < number; i++) {
    someArray.push([i]);
  }
}

qtyDdlOptions(qtyOptions, 100);

function populateQtyDdl(selector, items) {
  var $options = [];

  for (var i = 1; i < items.length; i++) {
    var item = [i];
    $options.push($('<option />', {
      text: item
    }));
  }
  $(selector).html($options);
}

populateQtyDdl('[data-role="qtyDdl"]', qtyOptions);

//I need to calc the subtotal based on price and qty. It works when hard coded, but not when I try to grab the price value.
function calcSubtotal() {
  value1 = $('[data-role="qtyDdl"] :selected').text();
  value2 = $('[data-role="price"]').text().slice(0);
  var x = value1 * value2;
  $('[data-role="subtotal"]').html("$" + x);
}

function calcTotal() {
  var x = $('[data-role="total"]').text();
  var value1 = $('[data-role="qtyDdl"] :selected').text();
  var value2 = $('[data-role="price"]').text().slice(0);
  var x = value1 * value2;
  $('[data-role="total"]').html("Total: $" + x);
}

$('[data-role="productsDdl"]').on("change", function() {

populatePrice('[data-role="productsDdl"]', '[data-role="price"]');
  
  
populateImage($('[data-role="productsDdl"] :selected'));
 
 
  //$('img').attr('src', "http://www.polyvore.com/cgi/img-thing?.out=jpg&size=l&tid=3024702");
  calcSubtotal();
})

$('[data-role="qtyDdl"]').on("change", function() {
  calcSubtotal();
})

//Changes the quantity in the cart and displays to customer
$('[data-role="addBtn"]').on("click", function() {
  var u = $('[data-role="productsDdl"] :selected').text();
  var x = $('[data-role="qtyDdl"] :selected').text();
  $('[data-role="qtyValue"]').html(x);

  var y = $('[data-role="productsDdl"] :selected').text();
  var z = $('[data-role="qtyDdl"] :selected').text();

  $('<li />', { 
    text: y + " was added to your cart. (Qty: " + z + ")"
  }).prependTo($('.cartList'));

  calcTotal();
})

//"Removes the product from the cart. 
$('[data-role="removeBtn"]').on("click", function() {
  $('[data-role="productsDdl"] :selected').text("Choose One");
  //$('[data-role="qtyDdl"] :selected').text("1");
  //$('[data-role="qtyValue"]').html(0);
  $('[data-role="subtotal"]').html("$0");
})

$('[data-role="cancel"]').on("click", function() {
  $('[data-role="qtyValue"]').html(0);
  $('.cartList').empty();
  $('[data-role="total"]').text("Total: $0");
})

 


Bài 22: Javascript Turorial App - Random Wikipedia App

Chưa có bình luận 1125
Javascript Cơ Bản, Javascript App, Web Javascript, Học Javascript, Học Js Cơ Bản, Javascript Kết Hợp Api, Javascript Với Api, Api App, Học Cơ Bản Js, Học Cơ Bản Javascript, Javascipt Covid, Covid Tracker Js, Website Với Javacript, Javacript Là Gì, Javascipt Api, Ja,

Javascript Turorial App - Ứng dụng Random Wikipedia App

Javascript Turorial App - Ứng dụng Random Wikipedia App

File index.html

<html>
	<head>
		<link rel="stylesheet" type="text/css" href="style.css">
		<link href="https://fonts.googleapis.com/css?family=Open+Sans:600,700" rel="stylesheet">
		<title>Wikipedia Random</title>
<style>
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    background-color: #f4f4f8;
    font-family: 'Raleway', sans-serif;
    font-weight: 500;
    min-height: 100vh;
    transition: all 0.3s;
    position: relative;
}

a, button {
    text-decoration: none;
    display: inline-block;
    padding: 10px 20px;
    border-radius: 30px;
    transition: all 0.3s;
}

.search-corner {
    width: 60%;
    margin: 0 auto;
    text-align: center;
    position: relative;
    padding-top: 15%;
    .search-box {
        position: relative;
        input {
            width: 100%;
            border: none;
            font-family: 'Raleway';
            font-weight: 300;
            font-size: 24px;
            padding: 10px 30px;
            border-radius: 30px;
            outline: none;
            box-shadow: 1px 3px 24px 3px #c4d5ef;
            transition: box-shadow 0.3s;
            &:focus {
                box-shadow: 1px 3px 40px 5px #c4d5ef;
            }
        }
        button {
            position: absolute;
            right: 0;
            top: 0;
            border: none;
            outline: none;
            background-color: #FF681D;
            font-family: 'Raleway';
            font-size: 24px;
            font-weight: 500;
            text-align: center;
            color: #fff;
            &:hover {
                background-color: darken(#FF681D, 10%);
            }
        }
    }
    &>p {
        padding-top: 30px;
        a {
            border: 1px solid #FF681D;
            color: #FF681D;
            font-weight: 500;
            margin: 20px 0 50px;
            &:hover {
                background-color: #FF681D;
                color: #fff;
                box-shadow: 1px 3px 20px 1px #ff8c54;
                transform: scale(1.1);
            }
        }
    }
    .search-result > div {
        background-color: #fff;
        padding: 10px 20px;
        margin: 30px 10px;
        border-radius: 6px;
        transition: all 0.3s;
        text-align: left;
        a {
            padding-left: 0;
            font-size: 18px;
            font-weight: 700;
            &:hover{
                color: #FF681D;
            }
        }
        &>p {
            font-size: 15px;
            font-weight: 500;
        }
        &:hover {
            box-shadow: 1px 3px 40px 5px #c4d5ef;
        }
    }
}

footer {
    .love {
        padding-top: 30px;
        font-weight: 500;
        font-size: 14px;
        text-align: center;
        a {
            padding: 0 0 20px;
            &:hover{
                color: #FF681D;
            }
        }
        .material-icons {
            color: #FF681D;
            font-size: 16px;
            animation: heartbeat 3s infinite;
        }
    }
    .notice {
        width: 70%;
        margin: 0 auto;
        border: 2px solid #c4d5ef;
        border-radius: 8px;
        padding: 8px;
        text-align: center;
        font-size: 14px;
    }
}

// *****************Media Queries for Responsive Layout

@media (max-width: 576px) {
    .search-corner {
        width: 80%;
        padding-top: 30%;
        .search-box {
            input, button {
                font-size: 18px;
            }
        }
        p > a {
            font-size: 14px;
        }
    }

    footer {
        font-size: 12px;
    }
}

@media (max-width: 321px) {
    .search-corner {
        width: 90%;
        p > a {
            font-size: 12px;
        }
    }
}


//Alternate layout using CSS Grid for the browsers that supports it.
@supports (display: grid) {
    body {
        display: grid;
        grid-template-columns: 1fr 2fr 1fr;
        grid-template-rows: 1fr auto;
    }

    .search-corner {
        grid-column: 2;
        align-self: center;
        justify-self: center;
        width: 90%;
        padding-top: 0;
    }

    footer {
        grid-column: 2;
        align-self: end;
        justify-self: center;
        .notice {
            display: none;
        }
    }

    @media (max-width: 921px) {
        body {
            grid-template-columns: 0.2fr 1fr 0.2fr;
        }
    }

    @media (max-width: 576px) {
        body {
            grid-template-columns: 0 1fr 0;
        }
    }
}


/*Beating heart animation keyframe*/
@keyframes heartbeat {
    0% {
        transform: scale(1.0);
    }
    5% {
        transform: scale(1.3);
    }
    10% {
        transform: scale(1.1);
    }
    20% {
        transform: scale(1.5);
    }
    30% {
        transform: scale(1.0);
    }
    100% {
        transform: scale(1.0);
    }
}
</style>
	</head>
	<body>
		<div id="container">
			<div class="search-corner">
  <div class="search-box">
    <form action="#" id="search" autocomplete="off">
      <input type="text" id="query" name="" placeholder="Search Wikipedia">
      <button type="submit">Search</button>
    </form>
  </div>
  <p>Or, <br> <a href="https://en.wikipedia.org/wiki/Special:Random" target="_blank">Read A Random Article</a></p>

  <div class="search-results">
    <h2 class="query-title"></h2>
    <div class="search-result r0"></div>
    <div class="search-result r1"></div>
    <div class="search-result r2"></div>
    <div class="search-result r3"></div>
    <div class="search-result r4"></div>
    <div class="search-result r5"></div>
    <div class="search-result r6"></div>
    <div class="search-result r7"></div>
    <div class="search-result r8"></div>
    <div class="search-result r9"></div>
  </div>

</div>

<footer>
  <p class="notice"><strong>Notice:</strong> Your browser doesn't support CSS Grid. Use a browser that supports it (E.g. Chrome, Mozilla etc) for best view.</p>
  <p class="love">Made with <i class="material-icons">favorite</i> by <a href="https://twitter.com/faahim01" target="_blank">Fahim</a></p>
</footer>
		</div>
		<script src="script.js"></script>
	</body>
</html>

File script.js

$(document).ready(function() {

	function fetchQuery() {

		$("#search").submit( function() {
			//Fetching the value from input element
			var searchQuery = document.getElementById('query').value;
			var wikiAPICall = "https://en.wikipedia.org/w/api.php?format=json&action=opensearch&search="+searchQuery;
			$.ajax({
				url: wikiAPICall,
				type: "GET",
				dataType: "jsonp",
				success: function(wikiData) {
					//Removing existing results
					$(".wow").remove();

					$(".search-corner").css("padding-top", "50px");

					//Checking weather any result found or not and showing the message
					if (wikiData[1][0] == undefined) {
						$(".query-title").text("No result found for '"+searchQuery+"' ????");
					} else {
						$(".query-title").text("Search results for '"+searchQuery+"'");
					}

					//Inserting search results into UI
					for (i=0; i<wikiData[1].length; i++) {
						$(".r"+i).html("<div class='wow fadeInUp'><a href='"+wikiData[3][i]+"' target='_blank'><p>"
							+wikiData[1][i]+"</p></a><p>"+wikiData[2][i]+"</p></div>");
					}
				}
			})
			event.preventDefault();
		});

	}
  
  //Calling the function.
	fetchQuery();
  new WOW().init();

});

 


Bài 23: Javascript Turorial App - Day of Birth App

Chưa có bình luận 1049
Javascript Cơ Bản, Javascript App, Web Javascript, Học Javascript, Học Js Cơ Bản, Javascript Kết Hợp Api, Javascript Với Api, Api App, Học Cơ Bản Js, Học Cơ Bản Javascript, Javascipt Covid, Covid Tracker Js, Website Với Javacript, Javacript Là Gì, Javascipt Api, Ja,

Javascript Turorial App - Viết ứng dụng tính cách qua ngày sinh của bạn 

File index.html

<html>
	<head>
		<link rel="stylesheet" type="text/css" href="style.css">
		<link href="https://fonts.googleapis.com/css?family=Open+Sans:600,700" rel="stylesheet">
		<title>Date of Birth App</title>
<style>
@import url('https://fonts.googleapis.com/css?family=Cabin');
* {
  box-sizing: border-box;
}
body {
  font-family: 'Cabin', sans-serif;
  margin: 0;
  background: #1abc9c;
}

.container {
  max-width: 950px;
  height: 100%;
  transition: all 1s ease;
  margin: 0 auto;
  padding: 80px;
  background: yellowgreen;
    box-shadow: inset 0px 0px 40px 40px #1abc9c; 
}

.container h1,
.container h4,
.container .selectWrapper {
    text-align: center;
}
.container h4 {
  color: brown;
}

/* Custom Select Styles*/
label.custom-select-wrapper {
   position: relative;
   font-size: 14px;
   display: inline-block;
  border: 1px solid white;
  margin: 20px;
  border-radius: 10px;
}

label span {
  padding: 20px;
}
.custom-select-wrapper select {
  width: 110px;
  padding: 8px 8px 8px 20px;
  cursor: pointer;
  display: inline-block;
  border: 1px solid lightgrey;
  border-radius: 0;
  margin: 0;
  outline:none; /* remove focus ring from Webkit */
  line-height: 1.2;
  background: white;   
  -webkit-appearance:none;
  -moz-appearance: none;
  -ms-appearance: none;
  appearance: none;
  border-radius: 10px;
}

/* Removing the dotted outline in Firefox */
.custom-select-wrapper select:-moz-focusring {
    color: transparent;
    text-shadow: 0 0 0 #000;
}


.custom-select-wrapper:after {
  content: "▾";
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  padding: 0 8px;
  line-height: 22px;
  background: white;
  color: lightgrey;
  pointer-events:none;
  border: 1px solid lightgrey;
  border-left: none;
  border-top-right-radius: 10px;
  border-bottom-right-radius: 10px;
}


.dayName {
  display: inline-block;
  text-transform: uppercase;
  color: white;
  font-size: 20px;
  padding: 0 10px;
}

#checkDay {
  display: block;
  background: #e67e22;
  color: white;
  width: 240px;
  padding: 15px;
  text-decoration: none;
  margin: 20px auto;
  text-align: center;
  text-transform: uppercase;
  border-radius: 10px;
}



</style>
	</head>
	<body>
		<div class="container">
  <h1>What does your Day of Birth say about you?!</h1>
  <h4>Discover what the Day of the Week you were born reveals about your personality</h4>
  <div class="selectWrapper">
<label class="custom-select-wrapper">
  <span>Birth Year</span>
  <select id='userYear'></select> 
</label>

  <label class="custom-select-wrapper"><span>Birth Month</span><select id='userMonth'></select> 
</label>

  <label class="custom-select-wrapper"><span>Birth Day</span><select id='userDay'> <option disabled="disabled" selected="selected">1</option></select> 
</label>
  </div>
<a href="#" id="checkDay"> Get Results</a>
<div id="result"></div>
</div>
		<script src="script.js"></script>
	</body>
</html>

File script.js

//PURE JS
var monthOptions = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var daysInMonth;
var userYearSelect = document.getElementById("userYear");
var userMonthSelect = document.getElementById("userMonth");
var userDaySelect = document.getElementById("userDay");
var yearSelected = "2017";
var monthSelected = "1";
var daySelected = "1";

userYearSelect.addEventListener("change", function() {
    yearSelected = userYearSelect.value;
    monthChange(); //update month (february) if leap year
});

function monthChange() {
      var daysInMonth = new Date(yearSelected, monthSelected, 0).getDate();
    userDaySelect.innerHTML = "";
    for (var i = 1; i <= daysInMonth; i++) {
        var el = document.createElement("option");
        el.textContent = i;
        el.value = i;
        userDaySelect.appendChild(el);
    };
}
userMonthSelect.addEventListener("change", function() {
    monthSelected = userMonthSelect.value;
    monthChange();
});

userDaySelect.addEventListener("change", function() {
    daySelected = userDaySelect.value;
});

for (var year = new Date().getFullYear(); year >= 1900; year--) {
    var el = document.createElement("option");
    el.textContent = year;
    el.value = year;
    userYearSelect.appendChild(el);
}

for (var i = 0; i < monthOptions.length; i++) {
    var el = document.createElement("option");
    el.textContent = monthOptions[i];
    el.value = i + 1;
    userMonthSelect.appendChild(el);
};

var checkDayButton = document.getElementById('checkDay');
checkDayButton.onclick = function(e) {
    e.preventDefault();
    var d = new Date(yearSelected + '-' + monthSelected + '-' + daySelected);
    day = d.getDay();

    function dayOfWeekAsString(day) {
        return [
            "<div class='dayName'>Sunday</div> <div class='dayDescription'><p>People who were born on Sundays have some of the most vibrant personality traits possible. These people tend to like their space when they have their alone time.</p><p>They also can get easily frustrated and leave things unfinished sometimes. Typically, are pretty sensitive and can sometimes dwell on what people say to you.</p><p>However, you have the brightest outlook on life, extremely positive, enjoy giving back to your community, and prefer to smile as often as you can.</p></div>",
            "<div class='dayName'>Monday</div><div class='dayDescription'><p>People who were born on a Monday have some of the most loving personality traits. You are family-oriented, very creative but like to keep those ideas to yourself, and tend to be a very sly negotiator when it comes to making sure that everyone is treated equally.</p><p>You are a person who strives for success and will assume the role of leadership if you have to.</p></div>",
            "<div class='dayName'>Tuesday</div><div class='dayDescription'><p>People who were born on the third day of the week, Tuesday, have some of the most successful traits to their personality. Although you are sensitive to criticism, you have high amounts of energy that drive you to meet your endgame goals sooner rather than later.</p><p>You are extremely successful in your career, speak as honestly as you possibly can, which can break peoples' hearts as you may know. You know right from wrong, and people can't help but be drawn to you.</p></div>",
            "<div class='dayName'>Wednesday</div><div class='dayDescription'><p>Those who claim Wednesdays as their day of birth have some of the most ideal traits to their personality.</p><p>You are very laid back, really love your work as well as the people you get to work with, are extremely universal when it comes to meeting different types of people, and you are an amazingly quick learner that makes you very good at your job.</p><p>However, you have a hard time staying organized sometimes. Otherwise, people love how relaxed you are.</p></div>",
            "<div class='dayName'>Thursday</div><div class='dayDescription'><p>People who were born on Thursdays have some of the most admirable personality traits. You are naturally charismatic as well as being a natural born leader.</p><p>You work very hard to meet your endgame goals, are mostly independent, extremely optimistic, and you give people your utmost respect when they deserve it. People are drawn to you for having such an adventurous lifestyle.</p></div>",
            "<div class='dayName'>Friday</div><div class='dayDescription'><p>Friday's children have some of the most creative personality traits. You tend to be one of the wisest people among your friends, are often told that you have a very old soul, extremely spiritual, and have an amazing sense of intuition.</p><p>However, you do not do well with setbacks and can obsess over disappointments that you've experienced in the past.</p></div>",
            "<div class='dayName'>Saturday</div><div class='dayDescription'><p>People who were born on a Saturday have some of these qualities to their personality: naturally, you are very confident but can sometimes present yourself as a snob to others.</p><p>You may also be somewhat negative to someone who asked for your opinion on something; you are very proud of your appearance and really love to take the time to look good. You are smart, trustworthy, and full of responsibility.</p></div>"
        ][day];
    }
    document.getElementById('result').innerHTML = 'You were born on: ' + dayOfWeekAsString(day);
}

 


Bài 24: Javascript Turorial App - Random Quote

Chưa có bình luận 1041
Javascript Cơ Bản, Javascript App, Web Javascript, Học Javascript, Học Js Cơ Bản, Javascript Kết Hợp Api, Javascript Với Api, Api App, Học Cơ Bản Js, Học Cơ Bản Javascript, Javascipt Covid, Covid Tracker Js, Website Với Javacript, Javacript Là Gì, Javascipt Api, Ja,

Javascript Turorial App - Viết ứng dụng Random câu nói hay bất hữu

Javascript Turorial App - Viết ứng dụng Random câu nói hay bất hữu

File index.html

<html>
	<head>
		<link rel="stylesheet" type="text/css" href="style.css">
		<link href="https://fonts.googleapis.com/css?family=Open+Sans:600,700" rel="stylesheet">
		<title>Random Quote</title>
<style>
 @import url('https://fonts.googleapis.com/css?family=Indie+Flower|Lato');

body {
  background-color: SaddleBrown;
  color: #fff;
  font-family: 'Lato', sans-serif;
}
.quote-font  {  
    font-family: 'Indie Flower', cursive;
    color:#3366CC;
  font-size: 1.5em;  
}
.wrapper  {
  min-width:300px;
  width:80%;
    margin: 5px auto 5px auto;
}
    .lightBack	{
        border: solid 0px;
        border-radius:13px;
        background-color:rgba(255,255,255,0.6);
        margin-left:auto;
        margin-right:auto;
        padding-left:1em;
        padding-right:1em;
        padding-top: .15em;
        width:80%;
        min-width:250px;
    }
</style>
	</head>
	<body>
		<div class="wrapper">  
<h1>Random Quote Generator</h1>
  <h2>For Free Code Camp</h2>
    <hr>
    <p>This is a tiny javascript "app" that display a random quote from an array of quotes.  Not sure why javascript has such a problem with random numbers.</p>
    <p>On PHP generating a random number between 1 and 10 is easy as pie:<br>
    <code>rand(1, 10);</code><br>
    In JavaScript however it's quite the pain in the ass:<br>
    <code>Math.floor((Math.random() * 10) + 1);</code>
    </p>
  
  <div class="lightBack">
            <p class="quote-font">
              <strong>" &nbsp;</strong>
                <script>
                  document.write(randomQuote());
                </script>
            </p>
          <p>
              <a href="https://twitter.com/share" class="twitter-share-button" data-size="large" data-show-count="false">Tweet</a><script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
          </p>

    </div>
  <p>&nbsp;</p>
 </div> 
		<script src="script.js"></script>
	</body>
</html>

File script.js

<script>
  function randomQuote() {
          //  generate a random number
          var randy;
          randy = Math.floor((Math.random() * 4));
  
          //  store the quotes in an array
          var quotes = [
            "Progress is impossible without change, and those who cannot change their minds cannot change anything.<br> -- George Bernard Shaw",
            "Change is the law of life. And those who look only to the past or present are certain to miss the future. <br>  --  John F. Kennedy",
            "To improve is to change; to be perfect is to change often. <br> -- Winston Churchill",
            "Everyone thinks of changing the world, but no one thinks of changing himself. --  Leo Tolstoy",
            "Smoking is hateful to the nose, harmful to the brain, and dangerous to the lungs.<br> -- King James I"
          ];

          //  write a random array item to the screen
           return quotes[randy];
        }
</script>

 


Bài 25: Javascript Turorial App - Day of Week App

Chưa có bình luận 1473
Javascript Cơ Bản, Javascript App, Web Javascript, Học Javascript, Học Js Cơ Bản, Javascript Kết Hợp Api, Javascript Với Api, Api App, Học Cơ Bản Js, Học Cơ Bản Javascript, Javascipt Covid, Covid Tracker Js, Website Với Javacript, Javacript Là Gì, Javascipt Api, Ja,

Javascript Turorial App - Ứng dụng hiển thị ngày trong tuần

File index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="description" content="JavaScript app that displays the day of the week!" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Day of the week</title>   
<style>

body {
&nbsp; font-family:Helvetica, Arial, sans-serif;
&nbsp; margin: 50px;
&nbsp; background:#fff;
}


#container {

&nbsp; width:650px;
&nbsp; height:350px;
&nbsp; background-color: #00ffff;
&nbsp; margin:auto; /* This centers block elements like divs */
&nbsp; border-radius: 30px;

}
h1 {
&nbsp; font-size: 47px;
&nbsp; font-weight: 600px;
&nbsp; color:#fff;
&nbsp; text-transform:uppercase;
&nbsp; margin-bottom:20px;
&nbsp; margin-left: 170px;
&nbsp; background:#0000ff;
&nbsp; padding: 10px;
&nbsp; border-radius: 5px;
&nbsp; display:inline-block;
}

#weekday {
&nbsp; font-size: 80px;
&nbsp; color:#dd5800;
&nbsp; font-weight: 800px;
&nbsp; margin-left: 170px;
}

#phrase {
&nbsp; font-size: 40px;
&nbsp; color:#0000ff;
&nbsp; font-weight: 800;
&nbsp; margin-left: 170px;
}
</style> 
    <link rel="stylesheet" type="text/css" href="mystyle.css">
  </head>

  <body>
      <div id ="container">
        <h1>Today is :</h1>
        <div>
          <span id="weekday">Display day of the week.</span><br/>
          <span id="phrase">Display a quote</span>
        </div>

      </div>  
  <script src="myscript.js"></script>

  </body>

</html>

File script.js

var d = new Date();
var weekday = new Array(7);
weekday[0]=  "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";

var date2 = new Date();
var weekday2 = new Array(7);
weekday2[0]=  "Time to chillax!";
weekday2[1] = "Monday morning blues!";
weekday2[2] = "Taco Time!";
weekday2[3] = "Two more days to the weekend.";
weekday2[4] = "The weekend is almost here...";
weekday2[5] = "Weekend is here!";
weekday2[6] = "Time to party!.";

var n = weekday[d.getDay()];
var n2 = weekday2[date2.getDay()];

var displayWeekday = document.getElementById('weekday');
var phrase = document.getElementById('phrase');

whatDayIsIt();

function whatDayIsIt() {
  
  displayWeekday.innerText = n ;
  phrase.innerText = n2;
  
}

 



CÔNG TY THIẾT KẾ WEBSITE CHUYÊN NGHIỆP

Kết nối với chúng tôi